java基础——泛型解析

泛型,编写的代码可以被很多不同类型的对象重用。简单泛型类的定义:

public class Generic<T> {
	public Generic(){
		this.info = null;
	}
	
	public Generic(T info){
		this.info = info;
	}
	
	public void setInfo(T info){this.info = info;}
	
	public T getInfo(){return this.info;}
	
	private T info;
}

用具体的类型替换类型变量(T)就可以实例化泛型类型:

为了更好的呈现泛型的原型首先新建一个student类:

public class Student {	
	public Student(){
		this.name = null;
		this.tall = 0;
	}
	
	public Student(String name,int tall){
		this.name = name;
		this.tall = tall;
	}
	
	public int getTall(){
		return this.tall;
	}
	public String getName(){
		return this.name;
	}
	
	public void getDescription(){
		System.out.println("学生:"+this.getName()+"\n身高:"+this.getTall()+"cm");
	}
	
	private String name;
	private int tall;
}

主类:

public class test {  
    public static void main(String[] args){ 
        /**************使用自定义泛型类*******************/
    	Student s = new Student("小卓",165);
        Generic<Student> info = new Generic<Student>(s);
        s.getDescription();
    }
}

结果:

学生:小卓
身高:165cm

注:也可以在普通类型中定义泛型方法

我们还可以对类型变量(T)进行限定,例如使T必须继承Comparable接口,这样才能对其数组进行排序:

public class Generic<T extends Comparable> {
      ... ...
}

当你定义了例子中的Generic泛型类后,你可以使用:

public class test {  
    public static void main(String[] args){ 
        /**************使用自定义泛型类的原型*******************/
    	Student s = new Student("小卓",165);
    	Generic info_raw = new Generic(s);
        Object ob = info_raw.getInfo();
        Student student = (Student)ob;
        student.getDescription();
    }
}

结果如上

这里没有使用<>传入对象类型,实例化时将结果进行了类型转换。泛型类的原型即将泛型中的T替换为了Object。

所有的类型查询只产生原始类型(以上面的s为例):

if(s instanceof Generic<Student>) //it's true

if(s instanceof Generic<String>) //it's also true

他们都是Generic类型

getClass方法总是返回原始类型:

Generic<Student> student = new Generic(....)

Generic<String> string= new Generic(....)

if(student .getClass() == string.getClass())  //true

使用泛型时需要注意:

1、不能抛出也不能捕泛型类实例

2、参数化类型的数组不合法

3、不能实例化类型变量

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值