开发者

what is the difference between these two object initialization in java?

开发者 https://www.devze.com 2023-01-27 13:25 出处:网络
If i use: HashMap<String, Integer> test = new HashMap<String, Integer>(); Or i use: HashMap test = new HashMap();

If i use:

    HashMap<String, Integer> test = new HashMap<String, Integer>();

Or i use:

    HashMap test = new HashMap();

Is there any difference on further methods that i can apply on test object. like test.put(), test.get() etc if initialized differently??

Also if i put something in test object e.g like:

    test.put("One", new Integer(5));
    test.put("Two", new Integer(4));
    test.put("Three", new Integer(3));

and display it as:

Set set = tokens.entrySet();

Iterator ik = test.iterator();

开发者_C百科    while(ik.hasNext()){
      Map.Entry me = (Map.Entry)ik.next();
      System.out.println(me.getKey() + " : " + me.getValue() );

The result is not sorted, restul is:

Three: 3 One: 5 Two: 1

What rule it does follow?? Is this normal behavior for the output to be randomly displayed??


In the first case Hashmap keys must be Strings and values must be Integers. The compiler will perform the respective type checking. In the second case any kind of objects can be used.

This is completely normal that your HashMap entries are printed in random order. If you want to preserve the order use LinkedHashMap instead.


In first example you can only put Strings as keys and Integers as values, but in second example you can put anything to the map and the compiler can't help you to get type safety.

Read more about how Java Generics works.


Yes, you'll get "random" iteration order when using HashMap. If you need a Map implementation with predictable iteration order, check out LinkedHashMap.


In the first case, key must be String and value must be Integer.

In the second case, key and value can be object of anytype.

HashMap and HashSet does not guarantee the insertion order. If you want it to remain in the order at which you insert the value, try LinkedHashMap. Much clearer was answered in previous StackOverflow question here


I think that depends on your usage , if you need a compiler to allow you to add only String as Key and Integer as value , then you need to specify both parameters type, otherwise if you need to pass anything without any restriction then use the second one.

0

精彩评论

暂无评论...
验证码 换一张
取 消