原始类型与<>之间的差别在泛型中 [英] Difference between raw types and <?> in Generics
问题描述
请告诉我以下的确切区别:
ArrayList list = new ArrayList();
和
的ArrayList<?> list = new ArrayList();
我无法弄清楚这两者之间的确切区别。
感谢...
ArrayList<?>
仅仅意味着任何类型。换句话说,任何类型的 ArrayList
都可以分配给这样的变量。这可能是 ArrayList<整数>
, ArrayList< JButton>
或其他。单独使用通配符,不使用关键字super(后跟一个类型),意味着您不能将 ADD 任何内容添加到定义为 ArrayList<?> $ c $的列表C>。
然而ArrayList
却意味着旧式的无类型 ArrayList
,您可以执行各种操作,包括 add
。
List<?>列表;
列表<整数> ints = new ArrayList< Integer>();
列表<整数> strings = new ArrayList< Integer>();
list = ints; // valid
list = strings; // valid
list.add(new); //编译错误
更新:
假设我有以下方法:
void insert(List list){
//通过列表循环,做任何你喜欢的
list.add(my string); //危险操作
}
现在如果我调用 insert ints)
编译器会生成一个警告,但不会阻止我将String添加到整数列表。改变方法如下:
void insert(List<?> list){
//循环列表,做任何你喜欢的
list.add(my string); //这个危险操作的编译器错误
}
会阻止我做这样的操作。
It may be asked somewhere but I could not find it.
Please tell me the exact difference between:
ArrayList list = new ArrayList();
and
ArrayList<?> list = new ArrayList();
I cannot figure out what is the exact difference between these two.
Thanks...
ArrayList<?>
simply means "any type." In other words, any type of ArrayList
can be assigned to such variable. That could be ArrayList<Integers>
, ArrayList<JButton>
or anything else. Using the wildcard alone, without the keyword super (followed by a type), means that you cannot ADD anything to the list defined as ArrayList<?>
. ArrayList
alone however, means the old style type-less ArrayList
which you can do all sorts of operations including add
.
List<?> list;
List<Integer> ints = new ArrayList<Integer>();
List<Integer> strings = new ArrayList<Integer>();
list = ints; // valid
list = strings; // valid
list.add("new"); // compile error
UPDATE:
Suppose I have following method:
void insert(List list) {
// loop through list, do whatever you like
list.add("my string"); // dangerous operation
}
Now if I call insert(ints)
compiler will generate a warning but will not prevent me of adding a String to a list of integers. Changing method to following:
void insert(List<?> list) {
// loop through list, do whatever you like
list.add("my string"); // compiler error on this dangerous operation
}
would prevent me of doing such an operation.
这篇关于原始类型与<>之间的差别在泛型中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!