Java泛型的简单应用

#源码

package cn.sxt.collection;
/*
 * 测试泛型
 * 作者:不忘初心
 * 
 */
/*   没有泛型的情况
public class TestGeneric {
	
	public static  void main(String[] Args) {
		//
		MyCollection  mc =new MyCollection();
		mc.set("xyz", 0);
		mc.set(0000,1);
		
	 Integer a = (Integer) mc.get(0);
	 String  b =  (String) mc.get(0);
		
		
	}

}
class  MyCollection{
	Object[] objs=new Object[5];
	public void set(Object obj,int index) {	
		objs[index]=obj;
	}
	public Object  get(int index) {
		return objs[index];
	}	
}
*/
/*
 * 使用泛型的情况
 */
public class TestGeneric {
	public static  void main(String[] Args) {
		//
		MyCollection <String> mc =new  MyCollection <>();  //添加泛型
		mc.set("xyz", 0);
//		mc.set(0000,1);
		
//	 Integer a = (Integer) mc.get(0);
	 String  b =  (String) mc.get(0);	
	 
	 System.out.println(b);
	}
}
class  MyCollection <E>{     //利用泛型定义类
	Object[] objs=new Object[5];
	public void set(E e,int  index) {	
		objs[index]=e;
	}
	public E  get(int index) {
		return (E) objs[index];
	}
}

#执行结果

在这里插入图片描述

发布了4 篇原创文章 · 获赞 0 · 访问量 70

猜你喜欢

转载自blog.csdn.net/qq_42849206/article/details/104051713