英文:
Java HashMap declaration
问题
你好,我对Java中HashMap的声明有一个问题。我想知道以下两种写法之间的区别是什么:
HashMap<String, Integer> map = new HashMap<>();
HashMap<String, Integer> map = new HashMap<String, Integer>();
大多数编程网站教授的是第二种写法。然而,第一种写法也能正常运行。我们是否应该偏好使用第二种写法?
英文:
Hi Guys I have a question about HashMap declaration in Java. I'd like to know what is the difference between:
HashMap<String,Integer> map = new HashMap<>();
and
HashMap<String,Integer> map = new HashMap<String,Integer>();
Most coding websites teach the second one. However, the first one works perfectly fine. Is there a reason we should use second one?
答案1
得分: 1
从Java 7开始,这两者之间没有任何区别。在Java 7之前,您必须在两侧的代码中都提到泛型类型参数,就像您在第二种情况下所示。但为了让开发人员在Java 7之后能够编写更少的代码,您只需在左侧定义一次。
在Java 7之前,您需要编写如下代码。
HashMap<String, Integer> map = new HashMap<String, Integer>(); //对于1.7版本以下的Java
在Java 7之后
HashMap<String, Integer> map = new HashMap<>(); //对于1.7版本以上的Java
英文:
There is no difference between the two of those since form the Java 7. Previously before Java 7 you must mention the Generic type parameters like in your second case in both sides.But to make it easier so that developer can write less code after Java 7 only you need to define it once in the left side.
Before Java Version 7 you need to code like below.
HashMap<String,Integer> map = new HashMap<String,Integer>();//For java versions below 1.7
After Java version 7
HashMap<String,Integer> map = new HashMap<>();//For java versions above 1.7
答案2
得分: 1
从技术上讲是没有的,然而自从Java 1.7版本以来,使用<>钻石操作符已成为一种惯例,它可以减小文本大小。
英文:
There is technically none, however since Java 1.7 it's a convention to use this <> diamond operator, it reduces the text size.
答案3
得分: 1
这被称为类型推断。
> 在 Java SE 7 之前的版本中,编译器能够推断泛型构造函数的实际类型参数,类似于泛型方法。然而,在 Java SE 7 及之后的版本中,如果使用 diamond(<>),编译器可以推断正在实例化的泛型类的实际类型参数。
new HashMap<String,Integer>()
- 在 Java 7 之前,类型参数是强制的。new HashMap<>()
- 自 Java 7 起,类型参数被推断出来。
推荐使用“钻石操作符”(<>
)因为更加简洁。实际上,并没有区别。
英文:
This is called Type Inference.
> Compilers from releases prior to Java SE 7 are able to infer the actual type parameters of generic constructors, similar to generic methods. However, compilers in Java SE 7 and later can infer the actual type parameters of the generic class being instantiated if you use the diamond (<>).
new HashMap<String,Integer>()
- The type parameter is mandatory before Java 7new HashMap<>()
- The type parameter is inferred as of Java 7
It's recommended to use the "diamond operator" (<>
) due to the brevity. Effectively, there is no difference.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论