简体   繁体   中英

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

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 eg 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();

    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 .

我认为这取决于你的用法,如果你需要一个编译器允许你只添加String作为Key和Integer作为值,那么你需要指定两个参数类型,否则如果你需要传递任何没有任何限制的东西然后使用第二个一。

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM