简体   繁体   English

java中这两个对象初始化有什么区别?

[英]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?? 像test.put(),test.get()等,如果初始化不同??

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(); 设置set = tokens.entrySet();
Iterator ik = test.iterator(); 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: 结果没有排序,restul是:

Three: 3 One: 5 Two: 1 三:3一:5两: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. 在第一种情况下,Hashmap键必须是字符串,值必须是整数。 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. 您的HashMap条目以随机顺序打印是完全正常的。 If you want to preserve the order use LinkedHashMap instead. 如果要保留订单,请改用LinkedHashMap。

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. 阅读有关Java Generics如何工作的更多信息。

Yes, you'll get "random" iteration order when using HashMap. 是的,在使用HashMap时,您将获得“随机”迭代顺序。 If you need a Map implementation with predictable iteration order, check out LinkedHashMap . 如果您需要具有可预测迭代顺序的Map实现,请查看LinkedHashMap

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

In the first case, key must be String and value must be Integer. 在第一种情况下,key必须是String,value必须是Integer。

In the second case, key and value can be object of anytype. 在第二种情况下,键和值可以是任何类型的对象。

HashMap and HashSet does not guarantee the insertion order. HashMap和HashSet不保证插入顺序。 If you want it to remain in the order at which you insert the value, try LinkedHashMap. 如果希望它保持插入值的顺序,请尝试使用LinkedHashMap。 Much clearer was answered in previous StackOverflow question here 在此之前的StackOverflow问题中回答了更清楚的问题

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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