泛型类
java
package com.test.generic;
//泛型类
public class Box<T> {
private T t;
public T getT() {
return t;
}
public void setT(T t) {
this.t = t;
}
public Box(T t)
{
this.t=t;
}
}
泛型接口
java
package com.test.generic;
//泛型接口
public interface MyList<E> {
E next();
}
java
package com.test.generic;
public class MyArrayList implements MyList<String>{
@Override
public String next() {
// TODO Auto-generated method stub
return null;
}
}
调用
java
package com.test.generic;
import java.awt.event.ItemEvent;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
import java.util.Map;
import java.util.Set;
import org.eclipse.jdt.internal.compiler.ast.ThisReference;
import com.sun.org.apache.xerces.internal.util.NamespaceContextWrapper;
public class TestGeneric {
public static void main(String[] args)
{
//泛型的作用之一:可以约束存放的类型 在编译期可以检查错误
ArrayList<String> arrayList=new ArrayList<String>();
arrayList.add("bb");
arrayList.add("aa");
for(String o: arrayList)
{
System.out.println(o);
}
//泛型中添加的参数不能是基本数据类型
ArrayList<Integer> arrayList2=new ArrayList<Integer>();
System.out.println(arrayList.getClass().equals(arrayList2.getClass()));
//去泛型化 泛型只是在编译期有效 一旦进入运行期,泛型会被擦除
Box<String> box=new Box<String>("hello");
System.out.println(box.getT());
}
}