java中的java5.0的泛型2(J2SE入門24)

來源:互聯網
上載者:User

泛型方法的定義
把數組拷貝到集合時,數組的類型一定要和集合的泛型相同。
<...>定義泛型,其中的"..."一般用大寫字母來代替,也就是泛型的命名,其實,在運行時會根據實際類型替換掉那個泛型。

<E> void copyArrayToList(E[] os,List<E> lst){
for(E o:os){
lst.add(o);
}
}
static <E extends Number> void copyArrayToList(E[] os,List<E> lst){
for(E o:os){
lst.add(o);
}
}
static<E extends Number & Comparable> void copyArrayToList(E[] os,List<E> lst){
for(E o:os){
lst.add(o);
}
}



受限泛型是指型別參數的取值範圍是受到限制的. extends關鍵字不僅僅可以用來聲明類的繼承關係, 也可以用來宣告類型參數(type parameter)的受限關係.例如, 我們只需要一個存放數位列表, 包括整數(Long, Integer, Short), 實數(Double, Float), 不能用來存放其他類型, 例如字串(String), 也就是說, 要把型別參數T的取值泛型限制在Number極其子類中.在這種情況下, 我們就可以使用extends關鍵字把型別參數(type parameter)限制為數字
只能使用extends不能使用 super,只能向下,不能向上。
調用時用<?>定義時用 <E>

泛型類的定義

1>類的靜態方法和靜態屬性都不能使用泛型,因為泛型類是在建立對象的時候產生的。

class MyClass<E>{
public void show(E a){
System.out.println(a);
}
public E get(){
return null;
}
}


受限泛型

class MyClass <E extends Number>{
public void show(E a){
}
}


泛型與異常

型別參數在catch塊中不允許出現,但是能用在方法的throws之後。例:

import java.io.*;

interface Executor<E extends Exception> {
void execute() throws E;
}

public class GenericExceptionTest {
public static void main(String args[]) {
try {
Executor<IOException> e = new Executor<IOException>() {
public void execute() throws IOException{
// code here that may throw an
// IOException or a subtype of
// IOException
}
}
e.execute();
} catch(IOException ioe) {
System.out.println("IOException: " + ioe);
ioe.printStackTrace();
}
}
}


泛型的一些局限型
1,catch不能使用泛型,在泛型集合中,不能用泛型建立對象,不允許使用泛型的對象。
2,不能執行個體化泛型
3,不能執行個體化泛型型別的數組
4,不能執行個體化泛型參數數
5,類的靜態變數不能聲明為型別參數類型

public class GenClass<T> {
private static T t; //編譯錯誤
}


6,靜態方法可以是泛型方法,但是不可以使用類的泛型。
7,泛型類不能繼承自Throwable以及其子類
public GenExpection<T> extends Exception{}   //編譯錯誤 
8,不能用於基礎類型int等

Pair<double> //error
Pair<Double> //right

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.