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

}
相关推荐
y1y1z3 小时前
Spring Security教程
java·后端·spring
MYMOTOE63 小时前
ISC-3000S的U-Boot 镜像头部解析
java·linux·spring boot
CoderYanger3 小时前
A.每日一题——3606. 优惠券校验器
java·开发语言·数据结构·算法·leetcode
谷哥的小弟3 小时前
Spring Framework源码解析——ConfigurableEnvironment
java·spring·源码
毕设源码-郭学长3 小时前
【开题答辩全过程】以 基于SpringBoot的宠物医院管理系统的设计与实现为例,包含答辩的问题和答案
java·spring boot·后端
利剑 -~3 小时前
设计java高并安全类
java·开发语言
CoderYanger3 小时前
D.二分查找-基础——744. 寻找比目标字母大的最小字母
java·开发语言·数据结构·算法·leetcode·职场和发展
柯南二号3 小时前
【后端】【Java】一文详解Spring Boot 统一日志与链路追踪实践
java·开发语言·数据库
CoderYanger3 小时前
贪心算法:2.将数组和减半的最少操作次数
java·算法·leetcode·贪心算法·1024程序员节
爱学java的ptt3 小时前
面试手撕排序
java·面试