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



Terrance Davis wrote:
| Here's a fun one. Using java 1.4.2 on my nifty new ibook this fills the
| Vector v with nulls:
|
| String s1[] =
| {"g","gt","f","a","z","e","qw","th","lslslslsl","this or that","this and
| that","1123","#4lskdjf","asdf","fdsa","zxq","zyx"};
|
| String o = "somekey";
| Vector v = new Vector();
|
| for(int x=0; x<s1.length; x++) {
| HashMap hm = new HashMap();
| v.add( hm.put(o, s1[x]) );
|
| if (v.get(x) == null) System.out.println("wowzers");
| }
| But this doesn't:
|
| String s1[] =
| {"g","gt","f","a","z","e","qw","th","lslslslsl","this or that","this and
| that","1123","#4lskdjf","asdf","fdsa","zxq","zyx"};
|
| String o = "somekey";
| Vector v = new Vector();
|
| for(int x=0; x<s1.length; x++) {
|
| HashMap hm = new HashMap();
| hm.put(o, s1[x]);
| v.add( hm );
|
| if (v.get(x) == null) System.out.println("wowzers");
| }
|
|
| I'd love to know if this is a bug or by design!

What you describe is exactly what I'd expect to see happen. The statement

v.add( hm );

adds the HashMap itself (guaranteed non-null). while

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

adds whatever HashMap.put() returns, which might or might not be null.

What *does* HashMap.put() return? The javadocs tell all:

public Object put(Object key,
Object value)

...

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

In other words, each call returns the value that the added value replaced. Since the HashMap is created anew each time around the loop, there is never a previous value to return, so put() always returns null.


| Perhaps my iBook is overheating....

Your brain is the more likely victim, I think.

Glen Fisher
_______________________________________________
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.