java[20]泛型的使用

泛型

泛型的基本概念:

泛型是javase 1.5的新特性,泛型的本质是参数化类型,也就是说所操作的数据类型被指定为一个参数,这种参数类型可以用在类、接口、和方法的创建中,分别称为泛型类、泛型接口和泛型方法。

JAVA语言引入泛型的好处是安全简单。

JAVAse1.5之前,没有泛型的情况下,通过对类object的引用来实现参数的‘任意化’,‘任意化’带来的缺点是要做显式的强制类型装换,而这种转换是要求开发者对实际参数类型可以预知的情况下进行的。对于强制类型转换错误的情况,编译器可能不提示错误,在运行的时候才出现异常,这是一个安全隐患。

泛型的好处是在编译的时候检查类型安全,并且所有的强制转换都是自动和隐式的,提高代码的重用率。

package jihelist;
import java.util.*;

public class fanxin {

	public static void main(String[] args) {
		// TODO Auto-generated method stub
		
		/*//强制类型装换
		ArrayList arrey = new ArrayList();
	    Dog dog1 = new Dog();
	    Dog dog2 = new Dog();
	    arrey.add(dog1);
	    arrey.add(dog2);
	    
		//取出   强转  
	    Dog tmp = (Dog)arrey.get(0);
	    
	    //编译也不会报错 安全隐患
	    Cat top = (Cat)arrey.get(1);*/
		
		
		//使用泛型,将类型作为参数传递,由Dog类集合成arrey,传递Dog
		ArrayList<Dog> arrey = new ArrayList<Dog>();
		Dog dog1 = new Dog();
		Dog dog2 = new Dog();
		arrey.add(dog1);
		arrey.add(dog2);
		//不需要再转换
		Dog tmp = arrey.get(0);
	

	}

}

class Cat {
	private String name;
	private String color;
	public String getName() {
		return name;
	}
	public void setName(String name) {
		this.name = name;
	}
	public String getColor() {
		return color;
	}
	public void setColor(String color) {
		this.color = color;
	}
	
	
	
	
	
}


class Dog{
	String name;
	int age;
	
	public String getName() {
		return name;
	}
	public void setName(String name) {
		this.name = name;
	}
	public int getAge() {
		return age;
	}
	public void setAge(int age) {
		this.age = age;
	}
	
	
	
	
}

示例2:

package jihelist;

public class fanxin2 {
	public static void main(String[] args) {
		// TODO Auto-generated method stub
		Gen<String> gen1 = new Gen<String>("aaa");
		gen1.showType();
		Gen<Integer> gen2 = new Gen<Integer>(2);
		gen2.showType();
		
		
		
	}
}



//  类似继承类 
class Gen<T>{
	private T o;
	public Gen(T xx){
		o = xx;
		
	}
	//
	public void showType() {
		System.out.println(o.getClass().getName());
	}
	
	
	
}

示例3:

package jihelist;

import java.lang.reflect.Method;

public class fanxin2 {
	public static void main(String[] args) {
		// TODO Auto-generated method stub
		/*Gen<String> gen1 = new Gen<String>("aaa");
		gen1.showType();
		Gen<Integer> gen2 = new Gen<Integer>(2);
		gen2.showType();*/
		Gen<Bird> gen1 = new Gen<Bird>(new Bird());
		gen1.showType();
		
		
		
	}
}


class Bird {
	public void aa() {
		System.out.println("aa");
		
	}
	public void count(int a,int b) {
		System.out.println(a+b);
	}
	
	
	
}



//  类似继承类   T是一个可变的类,类型不定 ;提高了重用率
class Gen<T>{
	private T o;
	public Gen(T xx){
		o = xx;
		
	}
	//
	public void showType() {
		System.out.println(o.getClass().getName());
		//通过反射机制,我们可以得到T这个类型的很多信息,比如成员、函数名
		Method m[] = o.getClass().getDeclaredMethods();
		
		//打印
		for (int i =0;i<m.length;i++) {
			System.out.println(m[i].getName());
		}
		
	}
	
	
	
}

猜你喜欢

转载自blog.csdn.net/qq_38125626/article/details/81182129