泛型
泛型
泛型类
定义泛型类就是在普通类前加一个或多个声明,下面是泛型的基本语法,通常是大写的字母,如E表示集合元素类型,泛型的参数可以有多个,就像方法的参数一样,多个参数变量之间用逗号隔开。
package Fl;
public class MyValue<T,U> {
private T value1;
private U value2;
public void setValue(T t,U u) {
this.value1=t;
this.value2=u;
}
public T getValue1() {
return value1;
}
public U getValue2() {
return value2;
}
}
package Fl;
public class Main {
public static void main(String[] args) {
//定义泛型变量,并指定泛型变量的值
MyValue<String,Integer> mv1=new MyValue<String,Integer>();
mv1.setValue("hello", 1);
System.out.println("第一个参数的值为"+mv1.getValue1()+"第二个参数的值为"+mv1.getValue2());
MyValue<Integer,String> mv2=new MyValue<Integer,String>();
mv2.setValue(2, "goodmorning");
System.out.println("第一个值为"+mv2.getValue1()+"第二个值为"+mv2.getValue2());
}
}
第一个参数的值为hello第二个参数的值为1
第一个值为2第二个值为goodmorning
泛型方法
对于泛型方法来说,可以在普通类中进行定义,也可以在泛型类中进行定义,泛型类型方法的变量实在“<>”中进行定义的,同时可以有多个类型变量,也是使用逗号隔开,
声明要在返回类型之前,这点要与泛型类区别开来。
public class Ftest {
//自定义泛型方法
public static <T> T getLast(T[] a){
//返回指定数组的最后一个值
return a[a.length-1];
}
public class Main {
public static void main(String[] args) {
// TODO Auto-generated method stub
String str[]= {
new String("第一个参数"),
new String("第二个参数"),
new String("第三个参数")
};
String strlast=Ftest.getLast(str);//调用静态方法
System.out.println("String数组最后一个值为:"+strlast);
Integer a[]= {1,2,3,4,5};
int d=Ftest.getLast(a);
System.out.println("Integer数组最后一个值为:"+d);
}
}
String数组最后一个值为:第三个参数
Integer数组最后一个值为:5
泛型接口
interface human<T>{
public void say(T t);
public void run();
}
//实现泛型接口,如果接口是泛型的话,实现它的子类也是泛型
public class people<T> implements human<T>{
public void say(T t) {
// TODO Auto-generated method stub
System.out.println(t);
}
@Override
public void run() {
// TODO Auto-generated method stub
System.out.println("正在跑步");
}
public static void main(String[] args) {
people<String> p=new people<String>();
p.say("hello");
}
类型变量的限制
希望类型变量有一定的范围,而不是所有变量都可以,这种情况下可以使用类型变量的限制来实现。
变量类型 extends 限定类型序列
public class people<T extends String,U extends Number>{
T name;
U age;
public people(T name,U age) {
this.name=name;
this.age=age;
}
public void statement() {
System.out.println("姓名:"+name+" 年龄:"+age);
}
public static void main(String[] args) {
people<String,Integer> p=new people<String,Integer>("xiaoli", 20);
p.statement();
}
}
泛型中的通配符
泛型中的继承和普通类中的继承是不同的,如果A类和B类是父类和子类的关系,则K<A>并不可以看成是G<B>如果要达到如此效果,则需要使用泛型的通配符“?”,例如以下代码。
LinkedList<?> list;
注意要点:
- 泛型通配符只能用于应用的声明中,不可以在创建对象的时候使用。
- 不能使用采用了泛型通配符的引用来调用使用泛型参数的方法。
import java.util.ArrayList;
public class Myprint {
public static void printMyValue(ArrayList<?> list) {
System.out.println("列表中的值为:"+list);
}
public static void main(String[] args) {
ArrayList list=new ArrayList();
list.add("hello");
list.add(2);
printMyValue(list);
}
}