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.
IndexProgramming Questions & HelpSyntax Questions › Trouble understanding HashMap() & Iterator
Page Index Toggle Pages: 1
Trouble understanding HashMap() & Iterator (Read 2009 times)
Trouble understanding HashMap() & Iterator
Aug 26th, 2009, 5:37pm
 
Hello,

I'm having a tough time understanding how HashMap() and Iterator work. Would anyone happen to know where I could find a "for dummies"-type explanation? Everything I've found so far has been rather confusing.

I'll keep looking at and trying to figure out the HashMapClass example included with Processing.
Re: Trouble understanding HashMap() & Iterator
Reply #1 - Aug 26th, 2009, 6:19pm
 
Re: Trouble understanding HashMap() & Iterator
Reply #2 - Aug 26th, 2009, 11:17pm
 
If you give a concrete example of what you want/need to do, perhaps we can show you some code to illustrate it.
Re: Trouble understanding HashMap() & Iterator
Reply #3 - Aug 27th, 2009, 3:10am
 
As the reference says:

Quote:
A HashMap stores a collection of objects, each referenced by a key. This is similar to an Array, only instead of accessing elements with a numeric index, a String is used.


You may have your reasons to use a HashMap and not a simple Array. It all depends on what you want to do...

The thing is, since it is a HashMap (and not an Array), you cannot iterate through it as you would do with an Array. You need an Iterator.

An iterator is just a tool that will help you to retrieve each element of the HashMap. It's a three-step procedure :

1. get an iterator from the hashmap
2. see if it can retrieve the next element
3. get the next element and back to step #2

You would do quite the same with an array (but the syntax is different, because Arrays and HashMaps are different) :

1. get the array's length
2. see if you have reached this length
3. get the current element and back to step #2
Re: Trouble understanding HashMap() & Iterator
Reply #4 - Aug 27th, 2009, 3:12am
 
HashMaps are just like dictionaries, they allow you to store a value against a given name. if you have the name you can get the value.

unfortunately you don't necessarily know which order it's storing your words in so you can't, for instance, ask for the first word (for that use a List)

using an iterator you can list all the entries in your dictionary one at a time but, like i say, you don't really have control over the ordering.

here's a java howto for HashMaps & Iterators which is a bit simpler than the Processing one. and less interesting to look at.

http://www.java-tips.org/java-se-tips/java.util/how-to-use-of-hashmap.html

(i think this is one of the places where java 6 syntax makes a lot of difference (although that example doesn't use it, and processing can't), i never did like iterators)

(oh, antiplastik just said pretty much the same thing)
Re: Trouble understanding HashMap() & Iterator
Reply #5 - Aug 27th, 2009, 4:16am
 
The last 2 posts gave good explanations of HashMap/Iterator and perhaps messing about with the code below might help.



Code:

class Employee {
 private String socialSecurityNumber;
 private String lastName;
 private String firstName;

 public Employee(String ssn, String lname, String fname){
   socialSecurityNumber = ssn;
   lastName = lname;
   firstName = fname;
 }
 public String getSocialSecurityNumber(){
   return socialSecurityNumber;
 }
 public String toString(){
   return socialSecurityNumber + " " + lastName + " " + firstName;
 }
}

void setup(){
 size(200,200);
 HashMap myMap;
 Employee emp, emp2;

 myMap = new HashMap();
 emp = new Employee ("12 45 67 89 C", "Smith", "John");
 myMap.put(emp.getSocialSecurityNumber(), emp);
 emp = new Employee ("11 22 33 44 Y", "Brown", "David");
 myMap.put(emp.getSocialSecurityNumber(), emp);

 if (myMap.containsKey("12 45 67 89 C")){
   emp2 = (Employee) myMap.get("12 45 67 89 C");
   println("Map contains key: " + emp2);
 }
 if (myMap.containsValue(emp)){
   emp2 = (Employee) myMap.get(emp.getSocialSecurityNumber());
   println("Map contains value: " +  emp2);
 }
 displayMapContents(myMap);
 println("Map has 2 entries" + myMap.size());
 myMap.clear();
 println("Map is now " + (myMap.isEmpty() ? "empty" : "not empty"));
}

void displayMapContents(HashMap hm){
 Iterator i = hm.entrySet().iterator();  // Get an iterator

 while (i.hasNext()){
   Map.Entry me = (Map.Entry)i.next();
   print(me.getKey() + " is ");
   println(me.getValue());
 }
}
Re: Trouble understanding HashMap() & Iterator
Reply #6 - Aug 27th, 2009, 10:19am
 
cool thank you all very much. I should have included the code I was working with, which is from page 112 of Visualizing Data:

Quote:
int teamCount = 30;
String[] teamNames;
String[] teamCodes;
HashMap teamIndices;

void setupTeams() {
  String[] lines = loadStrings("teams.tsv");
  
  teamCount = lines.length;
  teamCodes = new String[teamCount];
  teamNames = new String[teamCount];
  teamIndices = new HashMap();
  
  for (int i = 0; i < teamCount; i++) {
    String[] pieces = split(lines[i], TAB);
    teamCodes[i] = pieces[0];
    teamNames[i] = pieces[1];
    teamIndices.put(teamCodes[i], new Integer(i));
  }
}

int teamIndex(String teamCode) {
  Integer index = (Integer) teamIndices.get(teamCode);
  return index.intValue();
}


It talks about anchoring "both lists to the same order by mapping the teamcode to a particular team index (numbered 0 to 29), which ensures that data from each source is connected properly."

I'm gonna spend all day looking at this thread until it sinks in.


Re: Trouble understanding HashMap() & Iterator
Reply #7 - Aug 28th, 2009, 1:06am
 
I interpret the code as follow:
- read team information, a list of code & name pairs, whatever it is.
- store this information in arrays, for fast retrieval by index.
- store in a HashMap the index of each team, using the team code as key: thus, if one provides a code (be it 549, AZX or whatever), they can get the corresponding index, and thus the team name.
An alternative could be to store the name along the code in the hash map, but this solution has at least an advantage: it preserves the original team order, which might have an importance, and still allows iterating over that array in order.
Re: Trouble understanding HashMap() & Iterator
Reply #8 - Aug 30th, 2009, 8:06pm
 
Hello,

I think I've understood enough to get what's going on in the example in Visualizing Data. I just have a couple of questions:

Quote:
    emp2 = (Employee) myMap.get(emp.getSocialSecurityNumber());


Is this "casting"? Is casting the same as "wrapping" a variable type in another variable type? To cast into a class, do you just put the name of the class in ( ) immediately preceding the values you want to cast?

Quote:
void displayMapContents(HashMap hm){
  Iterator i = hm.entrySet().iterator();  // Get an iterator

  while (i.hasNext()){
    Map.Entry me = (Map.Entry)i.next();
    print(me.getKey() + " is ");
    println(me.getValue());
  }
}


In the line Map.Entry me = (Map.Entry)i.next(), is the iterator going to the next value in the hashmap, casting it into a Map.Entry variable, and then assigning it to the Map.Entry object named "me"?

Sorry for butchering the terminology.
Re: Trouble understanding HashMap() & Iterator
Reply #9 - Aug 30th, 2009, 11:43pm
 
Yes to all your questions! Smiley
With a precision. Casting isn't exactly ""wrapping" a variable type in another variable type", or rather there are restrictions in this wrapping. You cannot cast a PImage into a PVector for example. You can cast a generic type (eg. a List) to a specialized type (eg. an ArrayList). Cast of primitives (float to int) are a different problem.
In old Java (before 1.5, we still use the 1.4 syntax in Processing), lists, maps and other collections were generic (able to hold any kind of object), but for this, they hold actually only the Object type. Object is the fundamental class: all other classes are an extension of it (it has generic methods like toString, hash, etc.).
So when you do myMap.put(stuff), the stuff is internally stored as a plain anonymous Object. Although it has still information on what it is actually, the map see it only as an Object.
And when you do emp = myMap.get(id), you get an Object, but since you want an Employee, you have to cast it, to put the "virgin" object into shape.
Page Index Toggle Pages: 1