Mailing Lists: Apple Mailing Lists
Image of Mac OS face in stamp
Re: null you have, ... it null you don't
[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index]

Re: null you have, ... it null you don't



On Mar 2, 2004, at 3:58 PM, Terrance Davis wrote:

HashMap hm = new HashMap();
v.add( hm.put(o, s1[x]) );

According to the javadocs, Map.put returns

Returns:
previous value associated with specified key, or null if there was no mapping for key. A null return can also indicate that the map previously associated null with the specified key, if the implementation supports null values.

Thus, if hm did not contain the a value for the string you send, you will be adding null to the vector.

HashMap hm = new HashMap();
hm.put(o, s1[x]);
v.add( hm );

while here, you are adding the new hashmap, not the value formerly associated with the key s1[x].

I'd love to know if this is a bug or by design!

By design. Note that you are creating a brand new hashmap every time through the loop, so even though you are using the same key "somekey" stored in Object o, you are hitting a different hashmap each time.

If you meant to have these stored in the _same_ hashmap, move the declaration out of the loop, and consider what you want for keys, values, and items in the vector. (If what you want is a vector of the keys in the hashmap, you can get an unordered result via Map.keySet(), and there are Map implementations that remember the order of addition of keys.)

Scott
---
email@hidden
Java, Cocoa, WebObjects, and Database Consulting for the life sciences
_______________________________________________
java-dev mailing list | email@hidden
Help/Unsubscribe/Archives: http://www.lists.apple.com/mailman/listinfo/java-dev
Do not post admin requests to the list. They will be ignored.


References: 
 >null you have, ... it null you don't (From: Terrance Davis <email@hidden>)



Visit the Apple Store online or at retail locations.
1-800-MY-APPLE

Contact Apple | Terms of Use | Privacy Policy

Copyright © 2011 Apple Inc. All rights reserved.