当对象可以用作函数定义中的参数时,与无界类型相比可以接受任何对象时,需要通配符吗?
package wildCards;
import java.util.ArrayList;
import java.util.List;
public class NeedForWildCard {
public void processInput(List<String> values){
//Insted of List<String> we could have used List<object> and what is the need for wildcard in here?
for(String valueExtractor:values){
System.out.println("values="+valueExtractor);
}
}
public static void main(String[] args) {
ArrayList<Integer> valuesInteger=new ArrayList<>();
valuesInteger.add(100);
valuesInteger.add(200);
valuesInteger.add(300);
NeedForWildCard example=new NeedForWildCard();
example.processInput(valuesInteger);//valuesInteger is arguments since it is used in method call.
}
}
最佳答案
假设您有一个如下方法(带有通配符参数 Object
列表)
public void getList(List<Object> list){
...
}
然后用不同的方法执行以下操作
List<String> strList = new ArrayList<String>();
getList(strList);
第二行将出现编译错误
The method getList(List<Object>) in the type TESTClass is not applicable for the arguments (List<String>)
您不能用完全不同的对象来引用一个对象。
关于java - 当对象类型可用时,为什么需要通配符?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26362135/