Tôi có một lớp chung Foo<T>
và các loại được tham số Foo<String>
và Foo<Integer>
. Bây giờ tôi muốn đặt các loại tham số khác nhau vào một đơn ArrayList
. Cách làm đúng là gì?Vùng chứa các loại chung trong java
Candidate 1:
public class MMM {
public static void main(String[] args) {
Foo<String> fooString = new Foo<String>();
Foo<Integer> fooInteger = new Foo<Integer>();
ArrayList<Foo<?> > list = new ArrayList<Foo<?> >();
list.add(fooString);
list.add(fooInteger);
for (Foo<?> foo : list) {
// Do something on foo.
}
}
}
class Foo<T> {}
Candidate 2:
public class MMM {
public static void main(String[] args) {
Foo<String> fooString = new Foo<String>();
Foo<Integer> fooInteger = new Foo<Integer>();
ArrayList<Foo> list = new ArrayList<Foo>();
list.add(fooString);
list.add(fooInteger);
for (Foo foo : list) {
// Do something on foo.
}
}
}
class Foo<T> {}
Trong một từ, nó có liên quan đến sự khác biệt giữa Foo<?>
và loại thô Foo
.
Cập nhật:
Grep sự khác biệt giữa các ký tự đại diện kiểu tham số không giới hạn và các loại nguyên liệu là gì? trên this link có thể hữu ích.