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());	
		 
		
	}

}
相关推荐
lbb 小魔仙3 分钟前
【Java】Spring Cloud 微服务系统搭建:核心组件 + 实战项目,一步到位
java·spring cloud·微服务
a程序小傲10 分钟前
得物Java面试被问:流批一体架构的实现和状态管理
java·开发语言·数据库·redis·缓存·面试·架构
黎雁·泠崖14 分钟前
Java继承:成员变量访问(就近原则+this/super用法)
java·开发语言
别或许27 分钟前
python中的异步调用(直接使用教程)
java·前端·python
CodeAmaz34 分钟前
文件断点续传完整方案
java·文件断点上传
像少年啦飞驰点、34 分钟前
零基础入门 Spring Boot:从‘Hello World’到可部署微服务的完整学习路径
java·spring boot·web开发·编程入门·后端教程
m0_7482486540 分钟前
C++正则表达式攻略:从基础到高级应用
java·c++·正则表达式
墨雨晨曦8841 分钟前
leedcode刷题总结
java·开发语言
qq_12498707531 小时前
基于SpringBoot的闪电队篮球俱乐部管理系统的设计与开发(源码+论文+部署+安装)
java·数据库·spring boot·后端·spring·毕业设计·计算机毕业设计
a努力。1 小时前
中国邮政Java面试被问:MySQL的ICP(索引条件下推)优化原理
java·开发语言·数据仓库·面试·职场和发展·重构·maven