標籤:row next 變數 util over checked warnings 處理 ret
一、泛型類:
泛型是指適用於某一種資料類型而不是一個資料機構中能存不同類型
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 }
Java初學者筆記五:泛型處理