javaee 创建泛型类 泛型接口

泛型类

java 复制代码
package com.test.generic;

//泛型类
public class Box<T> {
	
	private T t;
	
	public T getT() {
		return t;
	}

	public void setT(T t) {
		this.t = t;
	}

	public Box(T t)
	{
		this.t=t;
	}

}

泛型接口

java 复制代码
package com.test.generic;


//泛型接口
public interface MyList<E> {
	
	E  next();

}
java 复制代码
package com.test.generic;

public class MyArrayList implements MyList<String>{
	@Override
	public String next() {
		// TODO Auto-generated method stub
		return null;
	}

}

调用

java 复制代码
package com.test.generic;

import java.awt.event.ItemEvent;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
import java.util.Map;
import java.util.Set;


import org.eclipse.jdt.internal.compiler.ast.ThisReference;

import com.sun.org.apache.xerces.internal.util.NamespaceContextWrapper;

public class TestGeneric {
	
	public static void main(String[] args)
	{
		//泛型的作用之一:可以约束存放的类型 在编译期可以检查错误
		 ArrayList<String> arrayList=new ArrayList<String>(); 
		 
		 
		 arrayList.add("bb");
		 
		 arrayList.add("aa");
		 
		 for(String o: arrayList)
		 {
			   System.out.println(o);
		 }
		 
		 //泛型中添加的参数不能是基本数据类型
		 ArrayList<Integer> arrayList2=new ArrayList<Integer>();
		 System.out.println(arrayList.getClass().equals(arrayList2.getClass()));
	
		 //去泛型化  泛型只是在编译期有效 一旦进入运行期,泛型会被擦除 
		 Box<String> box=new Box<String>("hello");
		 
		 System.out.println(box.getT());	
		 
		
	}

}
相关推荐
深栈解码36 分钟前
JMM深度解析(三) volatile实现机制详解
java·后端
liujing102329291 小时前
Day04_刷题niuke20250703
java·开发语言·算法
Brookty1 小时前
【MySQL】JDBC编程
java·数据库·后端·学习·mysql·jdbc
能工智人小辰1 小时前
二刷 苍穹外卖day10(含bug修改)
java·开发语言
DKPT1 小时前
Java设计模式之结构型模式(外观模式)介绍与说明
java·开发语言·笔记·学习·设计模式
缘来是庄1 小时前
设计模式之外观模式
java·设计模式·外观模式
知其然亦知其所以然2 小时前
JVM社招面试题:队列和栈是什么?有什么区别?我在面试现场讲了个故事…
java·后端·面试
harmful_sheep2 小时前
Spring 为何需要三级缓存解决循环依赖,而不是二级缓存
java·spring·缓存
星辰大海的精灵2 小时前
如何确保全球数据管道中的跨时区数据完整性和一致性
java·后端·架构
大大。2 小时前
van-tabbar-item选中active数据变了,图标没变
java·服务器·前端