java泛型剖析

一 java泛型是什么?泛型的好处是啥?
那些拥有Java1.4或更早版本的开发背景的人都知道,
1> 在集合中存储对象并在使用前进行类型转换是多么的不方便。泛型防止了那种情况的发生。
2> 它提供了编译期的类型安全,确保你只能把正确类型的对象放入集合中,避免了在运行时出现ClassCastException。
二 泛型类
当类中操作的引用数据类型不确定的时候,就用泛型类。

public class Tool{
    public T obj;
    public T getObject(){
        return obj;
    }
    public void setObject(T str){
        System.out.println("111");
        this.obj=str;
    }

}
public class Car{
    public Car() {
    super();
    }
}
public class Bus {
    public Bus() {
    super();
    }
}
public class GenericDemo {
    public static void main(String[] args) {

    Tool<Car>tool=new Tool<Car>();
    tool.setObject(new Car());
    Car car=tool.getObject();
    tool.setObject(New Bus());//wrong
    }
}

某类操作不确定的引用数据类型,就用泛型类。没有泛型之前,用Object,即Tool类如下:

public class Tool{

    public Object obj;

    public Object getObject(){
        return obj;
    }
    public void setObject(Object str){
        System.out.println("111");
        this.obj=str;
    }

}
public class GenericDemo{
    Tool  tool=new Tool ();
    tool.setObject(new Car());
    tool.setObject(new Bus());
    Car car=(Car)tool.getObject();}//需要强转。就和ArrayList加泛型效果一样,可在编译期检查。

这样的话,就可以往里添加任何对象,但是不安全。使用泛型类将运行时的安全检查转换到了编译时期,避免了强转的麻烦。
三 泛型方法
我们的目标是想在调用show函数时,能够分别输出String和Integer结果,而不是传给不同参数的show函数。

public class Car<T>{
    public int viechle;
    public String battery;
    public Car(int viechle, String battery) {
        super();
        this.viechle = viechle;
        this.battery = battery;
    }
    public void show(String str){
        System.out.println(str);
    }

    public void show1(Object str){
        System.out.println(str);
    }
    public void show2(T str){
        System.out.print(str);
    }
    public <E> void show3(E str){
    }
}
<pre name="code" class="java">public class GenericDemo {
    public static void main(String[] args) {

        Car<String>car=new Car<String>();
        car.show3("d23");
        car.show3(3);
                car.show3(new Integer(3));
    }

}

public class Car<T>{
    public int viechle;
    public String battery;
    public Car(int viechle, String battery) {
        super();
        this.viechle = viechle;
        this.battery = battery;
    }
    public void show(String str){
        System.out.println(str);
    }

    public void show1(Object str){
        System.out.println(str);
    }
    public void show2(T str){
        System.out.print(str);
    }
    public <E> void show3(E str){
    }
}
public class GenericDemo {
    public static void main(String[] args) {

        Car<String>car=new Car<String>();
        car.show3("d23");
        car.show3(3);
                car.show3(new Integer(3));
    }

}

当调用show1方法时,是可以实现我们的目标的,通过向上转型,Object可以转换为String和Integer类型。当调用show2方法时,由于Car已经定义为String类型,即T被转换为String类型,这样在调用show2方法时,只能输出字符串类型,输出整数类型就会提示错误。当然我们还有一种方法,就是使用泛型函数show3,这样就可以根据需要,在执行时给定输入类型,达到输入啥类型输出啥类型的效果。
四 泛型接口
将泛型定义在接口上,实现接口的类要给出具体的类型。

public interface Inter<T> {
    public <Q> void show(Q str);//泛型函数,依然适用于输出任何类型的参数。</span>
    public void show2(T str);

}
public class InterClass2 implements Inter<String> {//实现接口时,要在接口处(Inter)和实现函数处(show2)给出具体的类型。这样main函数中就可以放心的往里放String类型字符串。

    public static void main(String[] args) {
        // TODO Auto-generated method stub
        InterClass2 inter=new InterClass2();
        inter.show2("2");
    }

    @Override
    public void show2(String str) {
        // TODO Auto-generated method stub
        System.out.println(str);
    }

}
---------------------另外一种实现方式---------------------------------------------
public class InterClass<T> implements Inter<T> {//实现接口时,不给出具体类型,而是在main函数中,通过创建对象,确定泛型的具体类型。

    public void show2(T str) {
        // TODO Auto-generated method stub
        System.out.println(str);
    }
    public static void main(String[] args) {
    InterClass<Integer>inter=new InterClass<Integer>();
    inter.show2(2);}}

五 通配符
顾名思义,通通都能匹配的符号,用?来接收任何未知类型。以打印集合元素为例,我有ArrayList、ArrayList、HashSet三个集合,想通过printCollection函数,往里传啥类型就输出该类型所有元素。–可以用通配符来实现。

public class PrintColl {

    public static void printCollection(Collection<?>col){//如果只是ArrayList<String>和HashSet<String>集合,可用Collection<String>col方式(抽取共性)。但涉及到List和Set集合,并且有String和Integer不同类型,就得先抽取List和Set的共性:Collection,然后用通配符?表示String和Integer。
        Iterator<?>it=col.iterator();
        System.out.print(it.next());
    }
    public static void main(String[] args){
        ArrayList<String>a1=new ArrayList<String>();
        ArrayList<String>a2=new ArrayList<String>();
        HashSet<String>a3=new HashSet<String>();
        printCollection(a1);
        printCollection(a2);
        printCollection(a3);//这样的话,能全部通过编译,一次输出不同类型。
    }
}
-------------------------------------------------------------------------------------
//其实printCollection函数,可用泛型函数实现相同功能。
public static <T> void printCollection(T str){
    Iterator<T>it=col.iterator();
    System.out.print(it.next());
 }

六 泛型上下限
我有两个类Person和Dog,类Student继承了Person类。现在我想实现这样的功能:在调用printCollection函数时只打印Person及其子类对象,而不是一股脑统统的都打印出来。—-上(下)限。

public class Person {
    String name;
    int age;
    public Person(String name, int age) {
        super();
        this.name = name;
        this.age = age;
    }

}
public class Student extends Person {

    public Student(String name, int age) {
        super(name, age);
        // TODO Auto-generated constructor stub
    }

}
public class Dog {
    int age;
    public Dog(int age){
        this.age=age;
    }

}
public class PrintColl {

    public static void printCollection(Collection<? extends Person>col){
        Iterator<? extends Person>it=col.iterator();
        Person p=it.next();//确定上下限后,就可以用父类Person来接收所有子类型了,多好,将运行时的问题转换到了编译期。
         System.out.print(p);}
    public static void main(String[] args){
    ArrayList<Person>a1=new ArrayList<Person>();//ArrayList<Person>a1=new ArrayList<Student>()这样是不可以的,声明时集合中只能放Person对象,实体却把Student放进去了,不能同一代表。同样,反过来也不行,不能把实体Person放到Student的集合中去。两边泛型得匹配。
ArrayList<Dog>a2=new ArrayList<Dog>();
HashSet<Student>a3=new HashSet<Student>();
printCollection(a1);
//printCollection(a2);//添加a2就会出现问题,因为只能放Person及其子类。
printCollection(a3);}
}


------------在通过jdk两个例子解释下上下限-----------------------------------
Interface Collection<E>{
boolean addAll(Collection<?extends E>coll);//这样写,我可以往集合里添加E及其子类元素。如果是addAll(Collection<E>就只能往里添加E类元素,扩展性不强)
}
-----------------------------------------------------------------------------------------------------------------------------
class TreeSet<E>{
        TreeSet(Comparator<? super E>comparator);//若是TreeSet(Comparator<E>comparator)就只能用E类的比较器;若写成这种形式(下限),E的子类也可以用父类的比较器。
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值