Inserting Integers into a TreeMap
I want to store the IDs of items and their corresponding co-ordinates. For this, I'm using 开发者_JAVA技巧a TreeMap where Coordinates is a class containing int x and int y. Now, for inserting data into the map can I write:
treeMapObject.put(5,new BasicRow(30,90));
Or do I have to write:
treeMapObject.put(new Integer(5),new BasicRow(30,90));
I guess only the second one is correct because Maps deal with objects. But now the question is, say I have the following piece of code:
treeMapObject.put(new Integer(5),new BasicRow(30,90));
treeMapObject.put(new Integer(5),new BasicRow(45,85));
In such a case what will happen?
actually both versions are correct, because your Java compiler will perform what is called "autoboxing" for you: If you supply an int, where an Integer is required, java will automatically wrap that int in an Integer object for you. This works vice-versa as well (has been introduced in Java 5. If you'd use an older Java version that should not even compile.).
For your second question: The entry you added first will be overwritten.
yankee is right, both will work, because Java will autobox the integer values into an Integer
object.
Note that if you want to do this explicitly, it is better to write:
Integer a = Integer.valueOf(5);
instead of:
Integer a = new Integer(5);
If you use valueOf
, then class Integer
can avoid creating a new Integer
object, it will return a pre-existing Integer
object from its internal cache, which is more efficient than creating a new object.
There is a slight difference, which does not affect the behaviour of the map. In both cases, if you try to get the value for integer 5, the map will return that basic row.
The difference: the second line will always create a new instance of Integer
while the first one may insert an existing instance. But maps compare by equality, not by identity, so it actually doesn't matter. Just that the first line has a (very) small postive impact on memory consumption.
精彩评论