缓解警告消息“参考通用类型迭代器<e>应参数化”?</e>

时间:2013-12-02 08:39:38

标签: java compiler-warnings

  public static void updateCustomers(List custList) {
      Iterator itr = custList.iterator(); // line 1
      // other stuff
  }

以上代码在第1行显示警告信息,即

  

迭代器是原始类型。对泛型类型迭代器的引用   应该参数化

为了减轻警告我有两个选择

选项1: -

   public static void updateCustomers(List<Object> custList) {
      Iterator<Object> itr = custList.iterator(); // line 1
      // other stuff
  }

1选项: -

 public static void updateCustomers(List<?> custList) {
      Iterator<?> itr = custList.iterator(); // line 1
      // other stuff
  }

这两个选项都成功消除了警告消息,但我的问题是哪一个更好,为什么?

更新: -

我最同意

public static void updateCustomers(List<CustomerInfo> custList) {
    Iterator<CustomerInfo> ite = custList.iterator(); // line 1
    // other stuff
}

但是custList并不总是包含CustomerInfo。

4 个答案:

答案 0 :(得分:2)

OP更新中的代码是:

public static void updateCustomers(List<CustomerInfo> custList) {
    Iterator<CustomerInfo> ite = custList.iterator(); // line 1
    // other stuff
}

然后OP说:

  

但是custList并不总是包含CustomerInfo。

那么,custList可能包含一些与CustomerInfo无关的任意类型吗?如果是这样,那么声明参数List<?> custList可能是最好的。来自迭代器的元素将为Object,您必须进行instanceof检查和向下转换才能使用它们。

另一方面,custList是否包含某些特定子类型CustomerInfo的元素?如果是后者,则可以使方法本身具有通用性,如下所示:

public static <T extends CustomerInfo> void updateCustomers(List<T> custList) {
    Iterator<T> ite = custList.iterator(); // line 1
    // other stuff
}

答案 1 :(得分:0)

这样更好:

public static void updateCustomers(List<Customer> custList) {
    Iterator<Customer> ite = custList.iterator(); // line 1
    // other stuff
}

答案 2 :(得分:0)

我相信其他人可以更好地解释这一点,但要说明一点:如果你没有定义一个类型,编译器必须弄清楚他正在处理哪种类型。因此,如果您定义了类型安全类型。顺便说一句,对象仍然太笼统,你有没有一个名为Customer的类?

编辑:如果您有两个不同类型的列表,那么我建议您做什么:

public static void updateCustomers(ArrayList<CustomerInfo> custList, ArrayList<Whatever> whateverList) {
   Iterator<CustomerInfo> ite = custList.iterator(); // line 1
   Iterator<Whatever> iterator = whateverList.iterator(); // line 2
   // other stuff
}

答案 3 :(得分:0)

您是否考虑过将参数设置为参数化?

public static <T> void updateCustomers(List<T> custList) {
    Iterator<T> ite = custList.iterator();
    // other stuff
}
相关问题