泛型
是什么?
是一种未知的数据类型,当我们不知道使用什么类型时,便可以使用泛型。
泛型也可以看成一种变量,用来接收数据类型。
E e :Element 元素
T t :Type 类型
好处
- 避免了类型转化的麻烦,存的是什么类型,取出的就是什么类型
- 将运行期异常,提升到了编译期异常
弊端
- 泛型是什么类型,就只能存储什么类型。
书写形式
public class ArrayList<E>{
public boolean add(E e) {}
public E get(int index) {}
}
创建集合对象的时候,就会确定泛型的数据类型
ArrayList<String> list = new ArrayList<>();
public class ArrayList<String>{
public boolean add(String e) {}
public String get(int index) {}
}
当然遍历时候也要加上<类型>
Iterator<String> it = list.iterator();
while(it.hasNext()) {
System.out.println(it.next());
}
类
定义一个泛型类:
class GenericClass<E> {
private E name;
public E getName() {
return name;
}
public void setName(E name) {
this.name = name;
}
}
使用泛型类
public static void main(String[] args) {
// TODO Auto-generated method stub
//不写泛型默认为Object类型
GenericClass gc = new GenericClass();
gc.setName(123);
System.out.println(gc.getName());
GenericClass<String> gc1 = new GenericClass<>();
gc1.setName("string");
System.out.println(gc1.getName());
GenericClass<Integer> gc2 = new GenericClass<>();
gc2.setName(123345);
System.out.println(gc2.getName());
}
方法
定义一个含有泛型的方法:
定义含有泛型的方法:泛型定义在方法的修饰符合返回值之间
* 格式:
* 修饰符 <泛型> 返回值乐类型 方法名(参数列表(使用泛型)){
* 方法体;
* }
public class GenericMethod {
public <M> void show(M m) {
System.out.println(m);
}
}
使用含有泛型的方法
传递什么类型,泛型就是什么类型
public static void main(String[] args) {
GenericMethod gm = new GenericMethod();
gm.show(123);
gm.show(12.4);
gm.show("string");
gm.show(true);
}