<small>
泛型:可变参数化类型,暂时性的不指定类型,,当在指定场合下,则可以指定引用对应的类型
在类名后直接跟上<参数化类型E、T>
可变参数化类型,暂时性的不指定类型,
当在指定的场合下,则可以指定引用对应的类型。在类名后直接跟上<参数化类型E、T>在不指定泛型时,参数可为Object类型数据。一旦指定参数类型,则参数只能是对应类型的数据。
public class Point<E> {
private E x;
private E y;
public Point(E x, E y) {
this.x = x;
this.y = y;
}
public Point() {
}
public E getX() {
return x;
}
public void setX(E x) {
this.x = x;
}
public E getY() {
return y;
}
public void setY(E y) {
this.y = y;
}
public static void main(String[] args) {
/*
* 泛型:
* 参数化类型,暂时不指定类型时,
* 则类型可为Object
*
* 一旦泛型指定了参数类型,
* 则只能添加该类型的参数数据。
*/
Point point = new Point();
point.setX(1);
point.setY("二");
Point<People> point1 = new Point<People>();
point1.setX(new People());
point1.setY(new People());
}
}
- 泛型在迭代器中的使用:
- 因为迭代器是从集合中获取。
若集合不指定泛型,迭代器也不会指定泛型,迭代器非得指定泛型,则必定会导致集合元素类型转换异常。若集合指定泛型,则迭代器也要相应的指定泛型。- 作用:1、自动检测集合中的元素类型。
2、完成元素类型的强制类型转换过程。
public static void main(String[] args) {
//集合不指定泛型
Collection col = new ArrayList();
col.add("java");//String
col.add(1);//Integer
col.add(false);//Boolean
col.add(new People());//People
/*Iterator<People> ite = col.iterator();
while(ite.hasNext()){
People peo = ite.next();//类型转换异常。
System.out.println(peo);
}*/
```
//集合指定泛型:String类型
Collection<String> col1 =
new ArrayList<String>();
// col1.add(1);//已经无法添加非String类型的数据了。
col1.add("java");
col1.add("c#");
col1.add("IOS");
自动检测集合中的元素类型。
Iterator<String> ite = col1.iterator();
while(ite.hasNext()){
/若迭代器不指定泛型,则取出的元素是Object类型
若迭代器指定泛型,则可以直接取出对应泛型的类型数据。
/Object obj = ite.next();/
//完成元素类型的强制类型转换过程。
String str = ite.next();
}
}