Java初學者筆記五:泛型處理

來源:互聯網
上載者:User

標籤: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初學者筆記五:泛型處理

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.