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:

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");
}

If you read the JavaDoc for Map.put(key,value) you will see that it is defined to return the object that is CURRENTLY stored in the Map under supplied key. Since this is a brand new Map, obviously nothing is currently stored.

Consider this code:

Map m = new HashMap();
m.put( "key", "value1" );
System.out.println( m.put( "key", "value2" ) );

This will print "value1".

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");
}

This time through, you've filled your vector with s1.length references to the same instance of HashMap, and NOT the objects that you are putting in to your HashMap as I imagine you want. If after this code you said:

System.out.println( v.get(0) );

You might be surprised by the result!

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

by design :)

-wilhelm
_______________________________________________
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.