在 Java 中初始化泛型类型时什么时候需要尖括号?
When is angle bracket required in initializing generic type in Java?
下面三行都编译好了,有什么区别吗?如果不是,那么始终坚持使用第一个代码量最少的代码是一种很好的 Java 做法吗?
Map<String, String> m = new HashMap();
Map<String, String> k = new HashMap<>();
Map<String, String> l = new HashMap<String, String>();
而且我不明白为什么没有 <> 的 PriorityQueue 在我提供比较器 lambda 时无法编译:
PriorityQueue<Integer> pq = new PriorityQueue(); // compiled
PriorityQueue<Integer> pq = new PriorityQueue((x, y) -> (y - x)); // failed to compile
PriorityQueue<Integer> pq = new PriorityQueue<>((x, y) -> (y - x)); // compiled
这是完全等价的行(见diamond):
PriorityQueue<Integer> pq = new PriorityQueue<>((x, y) -> (y - x));
PriorityQueue<Integer> pq = new PriorityQueue<Integer>>((x, y) -> (y - x));
这也是等价的(都失败了):
new PriorityQueue((x, y) -> (y - x));
new PriorityQueue<Object>((x, y) -> (y - x));
他们失败了,因为你不能减去对象类型
您在 Map 案例中给出的第一种形式使用原始类型,将导致编译器警告。
$ cat D.java
import java.util.Map;
import java.util.HashMap;
class D {
Map<String,String> m = new HashMap();
}
$ javac D.java
Note: D.java uses unchecked or unsafe operations.
Note: Recompile with -Xlint:unchecked for details.
$ javac -Xlint:unchecked D.java
D.java:4: warning: [unchecked] unchecked conversion
Map<String,String> m = new HashMap();
^
required: Map<String,String>
found: HashMap
1 warning
所以,你不想那样做。你可以说它只是 Java 添加泛型之前的遗留问题。
这两种形式是等价的:
Map<String, String> k = new HashMap<>();
Map<String, String> l = new HashMap<String, String>();
在这两行的第一行中引入了 <>
语法以避免在第二行中重复;这是当今首选的语法。
<>
运算符从上下文中推断出所需的类型;需要的是一个从字符串到字符串的映射,所以这就是您得到的。 (这是一个非正式的描述,确切的规则在语言规范中)。
下面三行都编译好了,有什么区别吗?如果不是,那么始终坚持使用第一个代码量最少的代码是一种很好的 Java 做法吗?
Map<String, String> m = new HashMap();
Map<String, String> k = new HashMap<>();
Map<String, String> l = new HashMap<String, String>();
而且我不明白为什么没有 <> 的 PriorityQueue 在我提供比较器 lambda 时无法编译:
PriorityQueue<Integer> pq = new PriorityQueue(); // compiled
PriorityQueue<Integer> pq = new PriorityQueue((x, y) -> (y - x)); // failed to compile
PriorityQueue<Integer> pq = new PriorityQueue<>((x, y) -> (y - x)); // compiled
这是完全等价的行(见diamond):
PriorityQueue<Integer> pq = new PriorityQueue<>((x, y) -> (y - x));
PriorityQueue<Integer> pq = new PriorityQueue<Integer>>((x, y) -> (y - x));
这也是等价的(都失败了):
new PriorityQueue((x, y) -> (y - x));
new PriorityQueue<Object>((x, y) -> (y - x));
他们失败了,因为你不能减去对象类型
您在 Map 案例中给出的第一种形式使用原始类型,将导致编译器警告。
$ cat D.java
import java.util.Map;
import java.util.HashMap;
class D {
Map<String,String> m = new HashMap();
}
$ javac D.java
Note: D.java uses unchecked or unsafe operations.
Note: Recompile with -Xlint:unchecked for details.
$ javac -Xlint:unchecked D.java
D.java:4: warning: [unchecked] unchecked conversion
Map<String,String> m = new HashMap();
^
required: Map<String,String>
found: HashMap
1 warning
所以,你不想那样做。你可以说它只是 Java 添加泛型之前的遗留问题。
这两种形式是等价的:
Map<String, String> k = new HashMap<>();
Map<String, String> l = new HashMap<String, String>();
在这两行的第一行中引入了 <>
语法以避免在第二行中重复;这是当今首选的语法。
<>
运算符从上下文中推断出所需的类型;需要的是一个从字符串到字符串的映射,所以这就是您得到的。 (这是一个非正式的描述,确切的规则在语言规范中)。