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

}
相关推荐
前路不黑暗@26 分钟前
Java项目:Java脚手架项目的地图服务(十)
java·数据库·spring boot·笔记·学习·spring cloud·maven
014-code1 小时前
Redisson 常用技巧
java·redis
java干货1 小时前
明明删了数据,磁盘却满了?
java
之歆1 小时前
HA 高可用集群指南
java·开发语言
CHANG_THE_WORLD2 小时前
指针入门一
java·前端·网络
时艰.2 小时前
订单系统读写分离方案设计与实现
java
014-code2 小时前
MySQL 事务隔离级别
java·数据库·mysql
hrhcode2 小时前
【Netty】三.ChannelPipeline与ChannelHandler责任链深度解析
java·后端·spring·springboot·netty
invicinble3 小时前
关于学习技术栈的思考
java·开发语言·学习
json{shen:"jing"}3 小时前
分割回文串-暴力法
java·算法