>当你持有一组组件时,可以使用collction来存储
比如:
List list = new ArrayList();
list.add("xinwa1");
list.add("xinwa2");
String str = (String) list.get(0);
这时候编译器会出现异常,告诉我们:
Type safety: The method add(Object) belongs to the raw type List. References to generic type List should be parameterized
意思是说:这样写会有类型安全的异常,接下来使用泛型
List<String> list = new ArrayList<String>();
list.add("xinwa1");
list.add("xinwa2");
String str = list.get(0);
使用java反编译工具:JD-GUI 来查看
List list = new ArrayList();
list.add("xinwa1");
list.add("xinwa2");
String str = (String)list.get(0);
可以发现:java编译器对与泛型,编译之后并不存放相应的类型,使用泛型,编译器可以在编译时期就做好类型检查,避免发生ClassCastException异常
我们也可以自定义泛型
public class Some<T> {
private T thing;
public void setThing(T thing) {
this.thing = thing;
}
public T getThing() {
return thing;
}
}
Some<String> some = new Some<String>();
some.setThing("some thing");
String something = some.getThing();
反编译:
public class Some
{
public Some()
{
}
public void setThing(Object obj)
{
thing = obj;
}
public Object getThing()
{
return thing;
}
private Object thing;
}
还可以限制可指定的范围:
public class Some<T extends Serializable> {
private T thing;
public void setThing(T thing) {
this.thing = thing;
}
public T getThing() {
return thing;
}
}