Java泛型---定义与使用

什么是泛型,定义方法

    1)泛型类

/**
 * 定义为泛型类
 * 1.<>内放单个大写字母
 *    T --->Type
 *    K v --->Key Value
 *    E --->Element
 * 2.泛型不能使用在静态属性上,可以用于静态方法
 * 3.指定的类型不能为基本类型(byte short int long float double char boolean)
 * @author Administrator
 *
 */
public class GenericClass<T> {
	
	//private static T test; 不能用于静态属性
	private T obj;
	
	public GenericClass(){
		
	}

	public GenericClass(T obj) {
		this.obj = obj;
	}

	public T getObj() {
		return obj;
	}

	public void setObj(T obj) {
		this.obj = obj;
	}
}

    泛型类的使用与擦除

/**
 * 自定义泛型类的使用, 
 * 在声明的同时指定具体的类型, 
 * 但不能为基本类型(仅能操作引用类型)
 * 
 * 泛型的擦除
 *在使用泛型的时候没有定义具体的类型当做Object使用(类似,但不等同于,编译时不会进行类型检查),会弹出警告Waring
 * 
 * @author Administrator
 *
 */
public class MyStuApp {
	public static void main(String[] args) {
		//泛型的擦除,即不指定类型,当做普通类、方法使用
		GenericClass stu = new GenericClass();
		
		
		GenericClass<Integer> stu1 = new GenericClass<Integer>();
		stu1.setObj(1111);
		GenericClass<String> stu2 = new GenericClass<String>();
		stu2.setObj("aaa");

		Integer num = stu1.getObj();
		String str = stu2.getObj();
		System.out.println(num + "," + str);
	}
}

        2)泛型方法

        

import java.util.List;

/**
 * 非泛型类中定义泛型方法
 * 返回值前加泛型符号
 */
public class GenericMethod {
	//在返回值前加泛型符号即可将普通方法转换为泛型方法
	//可以用于静态方法
	public static<T> void test(T t){
		System.out.println(t+ "111");
	}
	//T的类型设定为List的实现类(子类)
	public static<T extends List> void test(T t){
		System.out.println(t+ "111");
	}
	
	public static void main(String[] args) {
		test("aaa");
	}
}

        3)泛型接口

/**
 * 自定义泛型接口
 * 接口(全局常量+公共抽象方法)
 * 1.泛型不能用于全局常量
 * 
 * 实现
 * 实现接口时规则与继承相同,继承类定义的数量>=接口
 * @author Administrator
 *
 */
public interface GenericInterface<T> {
	//全局常量
	/*public static final*/ int MAXVALUE=1024;
	//公共抽象方法
	/*public abstract*/ void compare(T t);
}


class C1 implements GenericInterface{

	@Override
	public void compare(Object t) {
		// TODO Auto-generated method stub
		
	}};
	
class C2<A> implements GenericInterface<String>{

		@Override
		public void compare(String str) {
			// TODO Auto-generated method stub
			
		}};

class C3<T ,A> implements GenericInterface<T>{

		@Override
		public void compare(Object t) {
			// TODO Auto-generated method stub
				
		}};

    

猜你喜欢

转载自blog.csdn.net/qq_30007589/article/details/80851168