Pergunta

I've been testing out HashMap recently and I've stumbled upon an interesting problem. I have an array, a3, that I have set some arbitrary values. I then take this array and put it into a HashMap instance map.

My problem is that when I assign an Object instance the value of put("a3", a3), I can't seem to print out the address of the instance.

For example:

HashMap<Object, Object> map = new HashMap<Object, Object>();
int[] a3 = new int[] {1, 2, 3, 4}; 

map.put("a3", a3); 

When I call System.out.println(map.put("a3", a3), I'm given an address in memory.

However, if I create an object instance and then try to print out that instance I get null.

Object copy = map.put("a3", a3); 
System.out.println(copy); 

Running the above segment gives me a value of null.

Any reason why both these statements, which appear identical, give me different results?

Foi útil?

Solução

Read the API Documentation for a HashMap. Null is returned if no value existed in the map that matches what you are inserting.

http://docs.oracle.com/javase/7/docs/api/java/util/HashMap.html#put%28K,%20V%29

So if "a3" existed in the map already, the you would get a return, but since it doesn't then you get back null. "a3" has been put into the map but you didn't print the map, you printed the return from put().

Outras dicas

As @James_Massey say, if you consult official documentation, you can see that the return value for put() method is:

the previous value associated with key, or null if there was no mapping for key. (A null return can also indicate that the map previously associated null with key.)

Licenciado em: CC-BY-SA com atribuição
Não afiliado a StackOverflow
scroll top