Java - dynamically create variable names

Associate
Joined
19 Jun 2006
Posts
162
Location
Swansea, Wales
Hi,

I am reading packets of a network and storing them via vectors.

Each packet has an ID number which is NOT unique to each packet but they are randomly spread through the traffic.

I want to read the ID number in each packet received and then create a vector with the name of that ID number. Or, if the vector already exists, pop the packet onto that vector.

E.g. (pseudo-code)

Packet.readID(packet);
Vector <idnumber> = new Vector();

Is this possible?

Any input appreciated.
 
yeah you have to use a map. make the key the ID and the value the object you create.

check javadocs for the map operations.

then just check the map before you make a new object, and change the value if it exists.
 
OK i looked at maps today and made my code but its not exactly what I want because i have only a single vector for all my packets whereas i wanted a vector for each id.

I have...

Code:
if (callMap.containsKey(callID)) {
  packetStack.add(packet);
} else {
  callMap.put(callID, packetStack);
  packetStack.add(packet);
}

But would prefer something like...

Code:
if (callMap.containsKey(callID)) {
  packetStack1.add(packet);
} else { /* new callID so create unique vector to which i can write packets */
  callMap.put(callID, packetStack2);
  packetStack2.add(packet);
}
 
I am taking 'packetStack' to be the vector name.

Code:
// if the ID number exists in the map, just add the packet to the vector already in the map
if (callMap.containsKey(callID)) {
   callMap.get(callID).add(packet);
}

// otherwise create new entry in the map and store the vector
// put the packet in the vector
else {
   // create the new Vector and store it in the map
   callMap.put(callID, new Vector());

   // store the packet
   callMap.get(callID).add(packet);
}
 
With the above code i get an error in Eclipse...

"The method add(Packet) is undefined for the type Object"

:(
 
Wimnat said:
callMap is defined:

Code:
Map callMap = new HashMap();

Thats your problem - Java has no way of knowing what you've put into the HashMap.

try:

Code:
HashMap<Integer,Vector> map = new HashMap<Integer,Vector>();
 
With generics, you (can) specify the type of variable a collection (list/array etc) contains.

Map<Integer, Vector> - a map that contains an Integer as the key and a Vector as the object stored in the map

Vector<Packet> - a Vector that contains objects of type Packet.
 
Back
Top Bottom