泛型
public class GenericTest {
public static void main(String[] args) {
ArrayList collection1=new ArrayList();
collection1.add(1);
collection1.add(1l);
collection1.add("abc");
int i=(Integer)collection1.get(1);
ArrayList<String> collection2=new ArrayList<String>();
//collection2.add(1);
//collection2.add(1l);
collection2.add("abc");
String element=collection2.get(1);
}
}
泛型的好处就是在定义的时候就决定接收的是什么类型,不用再类型转换。
定义了泛型,一个集合里面就只能存储同样的数据。
泛型是提供给javac编译器使用的,可以限定集合的存储类型。
泛型中的?通配符
集合类:
HashMap<String,Integer> maps=new HashMap<String,Integer>;
maps.put("aaa",22);
maps.put("bbb",33);
maps.put("ccc",55);
Set<Map.Entry<String,Integer>> entrySet=maps.entrySet();
for(Map.Entry<String,Integer>entry:entrySet){
System.out.println(entry.getKey()+":"+entry.getValue());
}
自定义泛型:
private static<T>T add(T x,T y){
return null;
}
调用时:add(3,5);//这里会自动装箱
add(3.5,3);--double和int交集就是number型
add(3,"abc");//去的类型是他们的交集--Object
交换数组中两个元素的位置
private static<T> void swap(T[] a,int i,int j){
T tmp=a[i];
a[i]=a[j];
a[j]=tmp;
}
调用:
swap(new String[]{"abc","xyz","itcast"},1,2);//泛型的类型必须的是引用类型,不能基础类型。int[]不会自动装箱,因为他本身就是一个对象了。
异常采用泛型:
private static<T extends Exception>sayHello()throws T{
try{
}catch(Exception e){
throw(T)e;
}
类型转换:
private static<T> autoConvert(Object obj){
return(T)obj;
}
调用:
Object obj="abc";
String x3=autoConvert(obj);
}
将任意类型的数组中的所有元素填充为相应类型的某个对象
private static<T> void fillArry(T[] a,T obj){
for(int i=0;i<a.length;i++){
a[i]=obj;
}
}
打印出任意参数化类型的集合中的所有内容
public static<T> void printCollecton(Collection<T> collection,T obj){
System.out.println(collection.size());
for(obj obj:collection){
System.out.println(obj);
}
}
泛型的类型:在类上定义
public class GenericDao<E>{
public void add(E x){
}
public E findById(int id){
return null;
}
public void delete(E obj){
}
public void delete(int id){
}
public void update(E obj){
}
public static<E>/*独立出来的,静态方法不行*/ void update(E obj){
}
public Set<E> findByConditions(String where){
return null;
}
}