【问题标题】:What is the convention for instantiating collections of user defined types?实例化用户定义类型集合的约定是什么?
【发布时间】:2023-04-03 07:13:06
【问题描述】:

我有一个名为 MatchingLine 的类

    public class MatchingLine implements Comparable
     {
        private String matchingLine;
        private int numberOfMatches;

        // constructor...
        // getters and setters...
        // interface method implementation...
     }

我在 ArrayList 中使用这个类如下 -

    ArrayList<MatchingLine> matchingLines = new ArrayList<MatchingLine>();

但是,Netbeans IDE 在此声明旁边放了一条注释并说,

   redundant type arguments in new expression (use diamond operator instead)

它建议我使用 -

    ArrayList<MatchingLine> matchingLines = new ArrayList<>();

我一直认为以前的风格是惯例?后一种风格是惯例吗?

【问题讨论】:

  • 顺便说一句,鼓励开发人员尽可能使用抽象类型的变量。所以Collection&lt;?&gt; varList&lt;?&gt; var 是首选。
  • @Alexey:在某些情况下首选。但是,根据您的操作, List> 可能无法使用。根本不可能向 List> 添加新对象(除了 null)。

标签: java list coding-style netbeans-7 java-7


【解决方案1】:
ArrayList<MatchingLine> matchingLines = new ArrayList<>();

这是 Java 7 中的一个新功能,称为 diamond operator

【讨论】:

    【解决方案2】:

    正如 Eng 所说,这是 Java 7 的一个新特性。

    它的编译与指定所有类型参数的完全声明的语句没有什么不同。这只是 Java 试图减少您必须输入的所有冗余类型信息的一种方式。

    在这样的语句中(仅用于说明;回调以接口最为人所知):

    Callback<ListCell<Client>,ListView<Client>> cb = new 
        Callback<ListCell<Client>,ListView<Client>>();
    

    在这个冗长的声明中,读者很清楚这些类型是什么。事实上,类型声明过多,使代码的可读性降低。所以现在编译器能够简单地使用类型推断和菱形运算符,让您可以简单地使用:

    Callback<ListCell<Client>,ListView<Client>> cb = new Callback<>();
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2013-04-17
      • 1970-01-01
      • 2019-11-24
      • 2015-12-08
      • 1970-01-01
      • 1970-01-01
      • 2018-09-19
      • 2011-07-31
      相关资源
      最近更新 更多