一、泛型类:
泛型是指适用于某一种数据类型而不是一个数据机构中能存不同类型
1 import java.io.*; 2 import java.nio.file.Files; 3 import java.nio.file.Paths; 4 import java.util.List; 5 6 class myClass<Type>{ 7 public Type[] tlist; 8 public Type tobject; 9 @SuppressWarnings("unchecked") 10 myClass(int maxsize,Type object){ 11 this.tlist = (Type[])new Object[maxsize]; 12 this.tobject = object; 13 } 14 public Type getMyObject() { 15 return this.tobject; 16 } 17 public Type[] getMyList() { 18 return this.tlist; 19 } 20 public void setMyObject(Type object) { 21 this.tobject = object; 22 } 23 } 24 25 public class test{ 26 public static void main(String args[]) throws IOException { 27 myClass<String> newone = new myClass<String>(5,"5"); 28 System.out.println(newone.getMyList()); 29 System.out.println(newone.getMyObject()); 30 newone.setMyObject("6"); 31 System.out.println(newone.getMyObject()); 32 } 33 }
1、知识点1--变量定义:
关于泛型变量(非数组)的定义:
1 class myClass<T>{ 2 public T t; 3 myClass(T newt){ 4 this.t = newt; 5 } 6 }
关于数据的泛型定义:
1 @SuppressWarnings("unchecked") 2 myClass(int maxsize){ 3 this.tlist = (Type[])new Object[maxsize]; 4 }
2、知识点2--泛型的实例化
这里需要显式的指出数据类型
1 myClass<String> newone = new myClass<String>(5,"5");
二、泛型接口:
1 public interface myinterface<T>{ 2 public T next(); 3 } 4 //接口需要继承 5 public class myclass implements myinterface<String>{//继承时候显式定义类型 6 private String[] stringlist=new String[]{"a1","b1","c1"}; 7 @Override 8 public String next(){ 9 Ramdom rand=new Random(); 10 return stringlist[rand.nextInt(3)]; 11 } 12 }
三、泛型方法:
1、在泛型类下的泛型方法:
泛型参数:
1 public void show(T t){ 2 System.out.println(t); 3 }
泛型返回值
1 public T getObject(){ 2 return this.t; 3 }
2、单独的泛型方法:
1 public stati <T> void out(T t){ 2 System.out.println(t); 3 }