You need to cast objects can come out of HashMap:
Code:
import java.util.Map;
import java.util.HashMap;
public class Test {
public static void main(String[] args) {
Map myMap = new HashMap(); // Program by interfaces.
myMap.put("One", new Integer(1));
myMap.put("Two", new Integer(2));
Integer associatedWithOne = (Integer)myMap.get("One"); // Note the cast
Integer associatedWithTwo = (Integer)myMap.get("Two"); // Note the cast
System.out.println(associatedWithOne);
System.out.println(associatedWithTwo);
}
}
It seems a little strange to begin with, but you soon get used to it (the next version of Java will make this much nicer).
Note - you can't put primitives (int, char, long) directly into a HashMap, you have to put them in 'wrapper' classes (Integer, Character, Long).
Bookmarks