Exception in thread "main" java.lang.ClassCastException: java.lang.Integer cannot be cast to java.lang.String at generic.BeforeGeneric.main(BeforeGeneric.java:24)
Exception in thread "main" java.lang.Error: Unresolved compilation problem: The method add(int, String) in the type ArrayList is not applicable for the arguments (int) at generic.GenericType.main(GenericType.java:8)
public static void main(String[] args) {
/**不指定泛型的时候*/
int i=Test.add(1, 2); //这两个参数都是Integer,所以T替换为Integer类型
Number f=Test.add(1, 1.2);//这两个参数一个是Integer,另一个是Float,所以取同一父类的最小级,为Number
Object o=Test.add(1, "asd");//这两个参数一个是Integer,另一个是String,所以取同一父类的最小级,为Object
/**指定泛型的时候*/
int a=Test.add(1, 2);//指定了Integer,所以只能为Integer类型或者其子类
int b=Test.add(1, 2.2);//编译错误,指定了Integer,不能为Float
Number c=Test.add(1, 2.2); //指定为Number,所以可以为Integer和Float
}
//这是一个简单的泛型方法
public static T add(T x,T y){
return y;
}
}
List listOfAnyType;
List listOfObject = new ArrayList();
List listOfString = new ArrayList();
List listOfInteger = new ArrayList();
listOfAnyType = listOfString; //legal
listOfAnyType = listOfInteger; //legal
listOfObjectType = (List) listOfString; //compiler error - in-convertible types
List listOfRawTypes = new ArrayList();
listOfRawTypes.add("abc");
listOfRawTypes.add(123); //编译器允许这样 - 运行时却会出现异常
String item = (String) listOfRawTypes.get(0); //需要显式的类型转换
item = (String) listOfRawTypes.get(1); //抛ClassCastException,因为Integer不能被转换为String
List listOfString = new ArrayList();
listOfString.add("abcd");
listOfString.add(1234); //编译错误,比在运行时抛异常要好
item = listOfString.get(0); //不需要显式的类型转换 - 编译器自动转换
通配符
通配符上界
常规使用
public class Test {
public static void printIntValue(List list) {
for (Number number : list) {
System.out.print(number.intValue()+" ");
}
System.out.println();
}
public static void main(String[] args) {
List integerList=new ArrayList();
integerList.add(2);
integerList.add(2);
printIntValue(integerList);
List floatList=new ArrayList();
floatList.add((float) 3.3);
floatList.add((float) 0.3);
printIntValue(floatList);
}
}
输出:
2 2
3 0
非法使用
public class Test {
public static void fillNumberList(List list) {
list.add(new Integer(0));//编译错误
list.add(new Float(1.0));//编译错误
}
public static void main(String[] args) {
List list=new ArrayList();
list.add(new Integer(1));//编译错误
list.add(new Float(1.0));//编译错误
}
}
public class Test {
public static void fillNumberList(List list) {
list.add(new Integer(0));
list.add(new Float(1.0));
}
public static void main(String[] args) {
List list=new ArrayList();
list.add(new Integer(1));
list.add(new Float(1.1));
}
}
在使用Eclipse进行开发的时候,出现了如下的问题:
Description Resource Path Location TypeThe project was not built due to "A resource exists with a different case: '/SeenTaoImp_zhV2/bin/seentao'.&
var grid = $('#datagrid');
var options = grid.datagrid('getPager').data("pagination").options;
var curr = options.pageNumber;
var total = options.total;
var max =