1.自定义泛型类,如果需要使用泛型变量的情况就可以定义泛型类。
泛型类的局限性:类实例化之后就已经确定了类型,无法再使用其他类型。使用泛型方法就可以解决这个局限性。
/**
* 泛型类的定义
*/
public class GenericClass<T> {
private T data;
public T method1(){
return data;
}
public void setValue(T data){
this.data=data;
}
}
调用:
GenericClass<String> genericClass=new GenericClass<String> ();
genericClass.setValue("");
2.自定义泛型方法
1.普通方法:
public <T> void method2(T data){
}
2.静态方法
public static <T> void method3(T data){
}
调用:
method2(10);
method2("test");
...
2.接口定义泛型方
/**
* 接口定义泛型
*/
public interface IGeneric<T> {
public void method1(T data);
}
//如果已经知道数据类型
class TestGeneric implements IGeneric<String>{
@Override
public void method1(String data) {
}
}
//数据类型未知
class TestGenericT<T> implements IGeneric<T>{
@Override
public void method1(T data) {
}
}
调用:
TestGeneric testGeneric=new TestGeneric() ;
testGeneric.method1("data");
TestGenericT<Integer> testGenericT=new TestGenericT<Integer>();
testGenericT.method1(1);
TestGenericT<String> testGenericT2=new TestGenericT<String>();
testGenericT2.method1("data");
2.泛型通配符 ?
//?号表示可以接收任何数据类型
public static void method1(List<?> data){
for(int k=0;k<data.size();k++){
Log.e("Debug",data.get(k).toString());
}
}
//调用
List<String> list=new ArrayList<>();
GenericClass.method1(list);
List<Integer> list2=new ArrayList<>();
GenericClass.method1(list2);
泛型通配符:
<? extends T>:向上限定,可以限定T类型或者T类型的子类。
< ? super T>:向下限定,可以限定T类型或者T类型的父类。
//父类
public class Father{
public void print(){
Log.e("Debug","Father==>print");
}
}
//子类类
public class Son extends Father{
public void print(){
Log.e("Debug","Son==>print");
}
}
//? extends T 向上限定,可以限定Father与它的子类
public static void method2(List<? extends Father> data){
for(int k=0;k<data.size();k++){
data.get(k).print();
}
}
//? super T 向下限定,可以限定Son类型或者Son类型的父类。
public static void method3(List<? super Son> data){
for(int k=0;k<data.size();k++){
}
}
调用:
GenericClass genericClass=new GenericClass();
GenericClass.Father father=genericClass.new Father();
GenericClass.Son son=genericClass.new Son();
List<GenericClass.Father> listFather=new ArrayList<>();
List<GenericClass.Father> listSon=new ArrayList<>();
//-------可以限定Father与它的子类----------
GenericClass.method2(listFather);
GenericClass.method2(listSon);
//-------可以限定Son类型或者Son类型的父类----------
GenericClass.method3(listFather);
GenericClass.method3(listSon);