概述
- 不知使用什么数据类型的时候可以使用泛型,如Collection< E >,泛型可以是任何数据类型
- 创建对象是时候就可以可以确定泛型是什么类型,如
Collection< Integer > coll = new ArrayList();
泛型确定为整型。把Integer传给E,E就变成了Integer。 - 创建集合对象不输入泛型也可以,此时可以是任何数据类型,但是,进行数据类型转换时会出现异常。
- 创建集合输入确定的类型,省去转换的麻烦。
泛型的定义和使用
类
public class GenericT {
public static void main(String[] args) {
GenericTt<String> G = new GenericTt();
G.setVal("Strings");
System.out.println(G.getVal());
}
}
class GenericTt<E>{
private E val;
public E getVal() {
return val;
}
public void setVal(E val) {
this.val = val;
}
}
//当泛型输入的是String代码可以翻译如下,相当于把E变成了String
/*
public class GenericT {
public static void main(String[] args) {
GenericTt<String> G = new GenericTt();
G.setVal("Strings");
System.out.println(G.getVal());
}
}
class GenericTt<String>{
private String val;
public String getVal() {
return val;
}
public void setVal(String val) {
this.val = val;
}
}*/
含有泛型的方法
- 格式 修饰词 <泛型> 返回值 方法名(参数列表){};
public class GenericT {
public static void main(String[] args) {
//GenericTt<String> G = new GenericTt();
//G.setVal("Strings");
//System.out.println(G.getVal());
GenericT.print("7676");
GenericT.<Double>print(78.5);//可以推断出来的类型不需要输入泛型
GenericT.print(78.35656);
}
static <M> void print(M a){
System.out.println(a);
}
}
含有泛型的接口
两种用法:
- public interface 接口< E >{},在写实现类的时候确定E的类型,
如
class 类名 implements 接口名 < String >{}。
public class GenericT {
public static void main(String[] args) {
/*GenericTt<String> G = new GenericTt();
G.setVal("Strings");
System.out.println(G.getVal());
GenericT.print("7676");
GenericT.<Double>print(78.5);//可以推断出来的类型不需要输入泛型
GenericT.print(78.35656);*/
DDDimpl d = new DDDimpl();
d.p("sfsfsfsf");
}
static <M> void print(M a){
System.out.println(a);
}
}
interface DD<E>{
void p(E s);
}
class DDDimpl implements DD<String>{
@Override
public void p(String s) {
System.out.println(s);
}
}
- 实现类和接口一样都用一样的泛型< E >,在实列化对象的时候确定类型
如:
public interface 接口< E >{}; class 类名 < E >implements 接口名 < String >{}; 在 new 的时候确定E的类型,与创建集合类类似,ArrayList< String > coll = new ArrayList();
public class ArrayList< E > extends AbstractList< E >
public class GenericT {
public static void main(String[] args) {
/*GenericTt<String> G = new GenericTt();
G.setVal("Strings");
System.out.println(G.getVal());
GenericT.print("7676");
GenericT.<Double>print(78.5);//可以推断出来的类型不需要输入泛型
GenericT.print(78.35656);*/
DDimpl<String> d = new DDimpl();
d.p("sfsfsfsf");
}
static <M> void print(M a){
System.out.println(a);
}
}
interface DD<E>{
void p(E s);
}
class DDimpl<E> implements DD<E>{
@Override
public void p(E s) {
System.out.println(s);
}
}