在 <> 中使用对象名称,因为 new ArrayList<String> 是正确的还是仅使用 <> 就可以?

Using object name with in the <> , as new ArrayList<String> is correct or it is ok to used only <>?

我创建了如下 (1) 方式的泛型,但是当 Sonar 给我错误来替换时,它有 (2) 。我需要知道,使用 <> 运算符创建泛型的最佳和正确方法是什么。

不合规的代码示例

List<String> strings = new ArrayList<String>();  // Noncompliant
Map<String,List<Integer>> map = new HashMap<String,List<Integer>>();  // Noncompliant

合规解决方案

List<String> strings = new ArrayList<>();
Map<String,List<Integer>> map = new HashMap<>();

声纳代码分析给出以下警告:

ava 7 引入了菱形运算符 (<>) 以减少泛型代码的冗长。例如,不必在声明和构造函数中都声明 List 的类型,您现在可以使用 <> 简化构造函数声明,编译器将推断类型。

请注意,当项目的 sonar.java.source 低于 7 时,此规则会自动禁用。

你是对的,使用菱形运算符(在 Java 7 中介绍)作为:

List<String> strings = new ArrayList<>();
Map<String,List<Integer>> map = new HashMap<>();

更好,因为让编译器根据声明的类型推断参数。

另请参阅:Java 7: Do we really need <> in the diamond operator?