We closed this forum 18 June 2010. It has served us well since 2005 as the ALPHA forum did before it from 2002 to 2005. New discussions are ongoing at the new URL http://forum.processing.org. You'll need to sign up and get a new user account. We're sorry about that inconvenience, but we think it's better in the long run. The content on this forum will remain online.
Page Index Toggle Pages: 1
Using Hashmaps (Read 1137 times)
Using Hashmaps
May 8th, 2009, 3:51pm
 
Does anybody know a good tutorial or explanation on how to use Hashmaps in processing? I read the Reference and the example by Dan Shiffmann but I have to admit i still dont get the whole idea of how to use it.

Im working with the Carnivore example and they use a hashmap to store the different pakets. Maybe somebody can explain whats happening here regarding the Hashmaps.

Thx!

Code:

import java.util.Iterator;
import org.rsg.carnivore.*;
import org.rsg.carnivore.net.*;
import org.rsg.lib.Log;

HashMap nodes = new HashMap();
float startDiameter = 20.0;
pakets[]

float x, y;

void setup(){
 size(800, 600);
 ellipseMode(CENTER);

 Log.setDebug(true); // Uncomment this for verbose mode
 CarnivoreP5 c = new CarnivoreP5(this);
 //c.setVolumeLimit(4);
}

void draw() {
 background(255);
 drawNodes();
}

// Iterate through each node
synchronized void drawNodes() {
 Iterator it = nodes.keySet().iterator();
 while(it.hasNext()){
   String ip = (String)it.next();
   println((String)it.next());
   float d = float(nodes.get(ip).toString());



// Use last two IP address bytes for x/y coords
   
   String ip_as_array[] = split(ip, '.');
   x = int(ip_as_array[2]) * width / 255; // Scale to applet size
   y = int(ip_as_array[3]) * height / 255; // Scale to applet size
   
   
   
// Use time
   
   String time_as_array[] = split(ip, '.');
   x = int(ip_as_array[2]) * width / 255; // Scale to applet size
   y = int(ip_as_array[3]) * height / 255; // Scale to applet size

   
   // Draw the node
   stroke(0);
   fill(color(100, 100, 100, 200)); // Rim
   ellipse(x, y, d, d); // Node circle
   noStroke();
   fill(color(100, 100, 100, 50));  // Halo
   ellipse(x, y, d, d);

   
 
 }  
}

// Called each time a new packet arrives
synchronized void packetEvent(CarnivorePacket packet){
// println("[PDE] packetEvent: " + packet);
//println(packet.dateStamp());
 // Remember these nodes in our hash map
 nodes.put(packet.receiverAddress.toString(), str(startDiameter));
 nodes.put(packet.senderAddress.toString(), str(startDiameter));
}
Re: Using Hashmaps
Reply #1 - May 9th, 2009, 1:43am
 
HashMaps in Java are what are called associative arrays in some other languages.
That's a Collection, allowing to associate a storage key (an identifier) with a value.
If you store a value with a key already existing in the map, the old value will be overwritten.
You can iterate on the whole map, like it is done here, getting the keys. With a given key, retrieving the value is very fast (unlike, say, an ArrayList where the collection have to be iterated to find the key, the HashMap gets the value at once).

HTH. If you need more details, just ask.
Re: Using Hashmaps
Reply #2 - May 9th, 2009, 1:59am
 
Thast mostly what i found out by reading the tutorials and Wikipedia.
But I got more questions of the usage of it.
if have no clue what happens here :

Iterator it = nodes.keySet().iterator();

or what   while(it.hasNext()){ means.

here : String ip = (String)it.next(); what is next ?

I guess in my case it would be maybe easier to just use an Array cause all i want to do is to draw all the pakets I recieve in a linear way. Dont need to search for information within these pakets.

How can I change it to an array? Any help would be great.

Re: Using Hashmaps
Reply #3 - May 9th, 2009, 3:02am
 
I've never used HashMaps, but was intrigued enough to look at the documentation...

If I've understood it correctly keySet() returns all the storage keys in nodes and iterator()... iterates over them.  I guess that's because you can't iterate through a set of keys using a standard int based loop where you reference the array elements with myArray[i].

hasNext() is a method from Iterator.  Since 'it' is an iteration over the keys in nodes then presumably it.hasNext() is equivalent to 'i < nodes.length' in a normal array.

So I'd guess this:

Iterator it = nodes.keySet().iterator();
while(it.hasNext()){


might be equivalent to this:

for(int i=0; i<myArray.length; i++){


Regarding:

String ip = (String)it.next();

next() is also a method from Iterator.  Looks like it's equivalent to myArray[i] in a standard array iteration...  i.e. it accesses the value associated with the storage key at this point in the iteration.

As I said I'm not 100% sure my interpretation of the documentation is correct, but it seems to make sense in the context of the code, and this should give you an idea of how to convert it to a normal array Wink

Documentation links:

http://java.sun.com/j2se/1.4.2/docs/api/java/util/Iterator.html

http://java.sun.com/j2se/1.4.2/docs/api/java/util/HashMap.html#keySet()
Re: Using Hashmaps
Reply #4 - May 9th, 2009, 3:06am
 
As I wrote, Iterator allows to iterate on the nodes of the HashMap, ie. to enumerate them, to process them all.
A HashMap has no method returning an iterator (unlike some other Collections), but fortunately there is a way to get all keys at once (keySet() method), and you can iterate on the result.
it.hasNext() checks if the iterator has walked all the values. It returns false if all keys have been iterated. it.next() allows to get the next value.
All this is roughly equivalent to a for() loop, if you want, something like
for (Iterator it = nodes.keySet().iterator(); it.hasNext(); it.next())
except that it.next() is also equivalent to ip = map[it] (pseudo-code!).

A simple array might not be suited to your needs, as the size won't adapt to the amount of data. If fixed size fits your needs, that's OK then.
Otherwise, you might also use an ArrayList.
Note that HashMap here has the side effect to erase/update the previous values. If you don't need this property, indeed you can use another data storage.
Re: Using Hashmaps
Reply #5 - May 9th, 2009, 4:56am
 
Thanks alot to both of you. i will take a deeper look at it this weekend. And maybe ask some more questions on sunday... but this already helped me to understand.
THX!
Re: Using Hashmaps
Reply #6 - May 10th, 2009, 3:02pm
 

I took a closer look at the programm itself and there are still some things unclear to me. But maybe thats the probleme and not the hashmap itself.


 nodes.put(packet.receiverAddress.toString(), str(startDiameter));
 nodes.put(packet.senderAddress.toString(), str(startDiameter));

this is the part where information is stored in the Hashmap. right?
the first is the key, the second the value. so the reciever and sender ip adress is stored with the value of the startDiameter? And how do i know they belong together? And what if i want to also save the time the paket was recieved. Using arrays i know that i just create a different array, and there i know, same index, means same paket.
How do i do it with a hashmap ? create a different hashmap and use the same key?  thats the part where i am confused cause

So to summarize the whole programm.
It creates a node for every ip adress and gives it the value of the diameter that updates during time. Am i right if i say that the programm overwrites a node as it has the same ip adress? so there is only 1 node for every ip adress?

I guess thats not what i want. I want a programm that leaves a mark on a timeline like graph everytime a packet is recieved. size and color of the mark should be changed by type etc.

So would it make sense to creat a class where i store all the informations of a recieved paket like, time, reciever and sender and so on? and use an array list to expand the list of objects ? so that i get an growing arraylist of objects containing all information of the recieved paket?


Thx again guys!
Re: Using Hashmaps
Reply #7 - May 11th, 2009, 1:36am
 
Cedric wrote on May 10th, 2009, 3:02pm:
I took a closer look at the programm itself and there are still some things unclear to me. But maybe thats the probleme and not the hashmap itself.


 nodes.put(packet.receiverAddress.toString(), str(startDiameter));
 nodes.put(packet.senderAddress.toString(), str(startDiameter));

this is the part where information is stored in the Hashmap. right

That's correct.

Cedric wrote on May 10th, 2009, 3:02pm:
the first is the key, the second the value. so the reciever and sender ip adress is stored with the value of the startDiameter And how do i know they belong together

The hasmap associates the key (the sender ip address in your case) with the value (the startDiameter parameter).

Cedric wrote on May 10th, 2009, 3:02pm:
And what if i want to also save the time the paket was recieved. Using arrays i know that i just create a different array, and there i know, same index, means same paket.
How do i do it with a hashmap create a different hashmap and use the same key  thats the part where i am confused cause

Creating a different hashmap and use the same value is an option, an alternative being to create a class that would have as part of its attributes both the startDiameter and the time at which the packet was received and use an instance of such a class as a value to associate with the sender ip address.

Cedric wrote on May 10th, 2009, 3:02pm:
It creates a node for every ip adress and gives it the value of the diameter that updates during time. Am i right if i say that the programm overwrites a node as it has the same ip adress so there is only 1 node for every ip adress

That's a correct interpretation of what would happen.

Cedric wrote on May 10th, 2009, 3:02pm:
I guess thats not what i want. I want a programm that leaves a mark on a timeline like graph everytime a packet is recieved. size and color of the mark should be changed by type etc.

So would it make sense to creat a class where i store all the informations of a recieved paket like, time, reciever and sender and so on and use an array list to expand the list of objects so that i get an growing arraylist of objects containing all information of the recieved paket

Yes. that's an option to consider, especially if you're interested in the order the packet is received (which you seem to be), as a hashmap makes no guarantees as to the order of the map and neither does it guarantee that the order will remain constant over time.
Re: Using Hashmaps
Reply #8 - May 11th, 2009, 12:13pm
 
big thanks tanepierre for answering all my questions. Seems like i wasnt that wrong. guess the problem was that i just wanted something else then the example did.

But i realized that it is even much easier and has alot of benefits to just parse the txt log fill carnivore can output then creating a graph in realtime.
Thanks again for the help Guys!
Page Index Toggle Pages: 1