java.util.HashMap is map with this behavior:
- Keys can`t be duplicated.
- Order of keys is unpredictable.
HashMap hm = new HashMap();
/* -- add keys and it values */
hm.put( "one", 1 );
hm.put( "two", 2 );
hm.put( "three", 3 );
hm.put( "three", 5 ); // exists already -> ignore
hm.put( "three", 3 ); // exists already -> ignore
hm.put( "four", null );
/* elements count */
System.out.println( "Elements count = " + hm.size() );
/* check if contains key */
System.out.println( "Contains \"one\" = " + hm.containsKey( "one" ) );
/* get value for key */
System.out.println( "\"one\" value = " + hm.get( "two" ) );
/* -- write all keys and all values */
System.out.println( "Keys = " + new ArrayList( hm.keySet() ).toString() );
System.out.println( "Values = " + new ArrayList( hm.values() ).toString() );
The output:
Elements count = 4
Contains "one" = true
"one" value = 2
Keys = [two, one, three, four]
Values = [2, 1, 3, null]
See that the order of elements are different than you have inserted. Also two items were omitted.
No comments:
Post a Comment