通配符,java中的泛型
我在countList方法上得到一个编译时错误通配符,java中的泛型,java,generics,Java,Generics,我在countList方法上得到一个编译时错误 public static void countList( List<? extends Number> list, int count ){ for( int i = 0; i < count; i++ ){ list.set(i, i-1); } } public static void clearList( List<?extends Number> li
public static void countList( List<? extends Number> list, int count ){
for( int i = 0; i < count; i++ ){
list.set(i, i-1);
}
}
public static void clearList( List<?extends Number> list){
list.clear();
}
publicstaticvoidcountlist(List,因为它是一个“扩展数字的东西,但我不知道是什么”的列表。你不能把整数放进去,如果它实际上是一个双精度的列表呢
List<Double> list = new ArrayList<Double>();
list.add(Double.valueOf(4.5);
countList(list, 1);
Double d = list.get(0); //what happens here? You put an Integer in there! class cast exception
List List=new ArrayList();
列表。添加(双值)(4.5);
计数表(表1);
Double d=list.get(0);//这里发生了什么?您在其中放入了一个整数!类强制转换异常
您可以清除列表,因为对于该操作,实际存在的数字子类型并不重要。清除就是清除。因为它是一个“扩展数字的东西,但我不知道是什么”的列表。您不能只将整数放入其中,如果它实际上是一个双精度列表呢
List<Double> list = new ArrayList<Double>();
list.add(Double.valueOf(4.5);
countList(list, 1);
Double d = list.get(0); //what happens here? You put an Integer in there! class cast exception
List List=new ArrayList();
列表。添加(双值)(4.5);
计数表(表1);
Double d=list.get(0);//这里发生了什么?您在其中放入了一个整数!类强制转换异常
你可以清除列表,因为在那个操作中,哪个子类型实际上在里面并不重要。清除是清楚的。
< P>问题是编译器不知道在运行时,由于类型擦除,将添加什么类型的数字。考虑这个例子:
public static void main(String[] args) {
List<Integer> intList= new ArrayList<Integer>();
// add some Integers to the list here
countList(intList, 4);
}
public static void countList( List<? extends Number> list, int count ) {
for( double d = 0.0; d < count; d++ ){
list.set((int)d, d-1); // problem at d-1, because at runtime,
// the double result of d-1 will be autoboxed to a Double,
// and now you have added a Double to an Integer List (yikes!);
}
}
publicstaticvoidmain(字符串[]args){
List intList=new ArrayList();
//在此列表中添加一些整数
计数表(intList,4);
}
公共静态空洞计数(列表< P>)问题是编译器不知道在运行时,由于类型擦除,将向列表添加什么类型的数字。
public static void main(String[] args) {
List<Integer> intList= new ArrayList<Integer>();
// add some Integers to the list here
countList(intList, 4);
}
public static void countList( List<? extends Number> list, int count ) {
for( double d = 0.0; d < count; d++ ){
list.set((int)d, d-1); // problem at d-1, because at runtime,
// the double result of d-1 will be autoboxed to a Double,
// and now you have added a Double to an Integer List (yikes!);
}
}
publicstaticvoidmain(字符串[]args){
List intList=new ArrayList();
//在此列表中添加一些整数
计数表(intList,4);
}
publicstaticvoidcountlist(列表)我认为您需要一个整数,而不是一个int@Fido我将其更改为list.set(I,newinteger(I-1));它不起作用在java中泛型是令人困惑的,即使在阅读了几遍泛型指南之后,我想您可能会想阅读以下内容:我想您需要的是一个整数,而不是一个整数int@Fido我将其更改为list.set(I,新整数(I-1));它在java中不起作用泛型即使在多次阅读泛型指南后仍然令人困惑,我想您可能想阅读以下内容: