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

}
相关推荐
CryptoRzz21 分钟前
欧美(美股、加拿大股票、墨西哥股票)股票数据接口文档
java·服务器·开发语言·数据库·区块链
杂货铺的小掌柜41 分钟前
apache poi excel 字体数量限制
java·excel·poi
大厂码农老A1 小时前
你打的日志,正在拖垮你的系统:从P4小白到P7专家都是怎么打日志的?
java·前端·后端
艾菜籽1 小时前
Spring MVC入门补充2
java·spring·mvc
爆更小哇1 小时前
统一功能处理
java·spring boot
程序员鱼皮1 小时前
我造了个程序员练兵场,专治技术焦虑症!
java·计算机·程序员·编程·自学
n8n2 小时前
SpringAI 完全指南:为Java应用注入生成式AI能力
java·后端
不爱编程的小九九2 小时前
小九源码-springboot082-java旅游攻略平台
java·开发语言·旅游
只是懒得想了2 小时前
用C++实现一个高效可扩展的行为树(Behavior Tree)框架
java·开发语言·c++·design-patterns
码农阿树2 小时前
Java 离线视频目标检测性能优化:从 Graphics2D 到 OpenCV 原生绘图的 20 倍性能提升实战
java·yolo·目标检测·音视频