Java哈希映射声明

huangapple go评论70阅读模式
英文:

Java HashMap declaration

问题

你好,我对Java中HashMap的声明有一个问题。我想知道以下两种写法之间的区别是什么:

  1. HashMap<String, Integer> map = new HashMap<>();
  2. 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&lt;String,Integer&gt; map = new HashMap&lt;&gt;();

and

HashMap&lt;String,Integer&gt; map = new HashMap&lt;String,Integer&gt;();

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&lt;String,Integer&gt; map = new HashMap&lt;String,Integer&gt;();//For java versions below 1.7

After Java version 7

HashMap&lt;String,Integer&gt; map = new HashMap&lt;&gt;();//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&lt;String,Integer&gt;() - 在 Java 7 之前,类型参数是强制的。
  • new HashMap&lt;&gt;() - 自 Java 7 起,类型参数被推断出来。

推荐使用“钻石操作符”(&lt;&gt;)因为更加简洁。实际上,并没有区别。

英文:

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&lt;String,Integer&gt;() - The type parameter is mandatory before Java 7
  • new HashMap&lt;&gt;() - The type parameter is inferred as of Java 7

It's recommended to use the "diamond operator" (&lt;&gt;) due to the brevity. Effectively, there is no difference.

huangapple
  • 本文由 发表于 2020年10月22日 19:13:28
  • 转载请务必保留本文链接:https://go.coder-hub.com/64481039.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定