Java 泛型方法和構造函數

2018-01-19 11:18 更新

Java面向對象設計 - Java泛型方法和構造函數

泛型方法

我們可以在方法聲明中定義類型參數,它們在方法的返回類型之前的尖括號中指定。

包含泛型方法聲明的類型不必是泛型類型。

我們可以在非靜態(tài)方法聲明中使用為泛型類型指定的類型參數。

例子

以下代碼顯示如何為方法m1()定義新的類型參數V.

新類型參數V強制方法m1()的第一個和第二個參數為相同類型。

第三個參數必須是相同的類型T,這是類實例化的類型。

class MyBag<T> {
  private T ref;

  public MyBag(T ref) {
    this.ref = ref;
  }

  public T get() {
    return ref;
  }

  public void set(T a) {
    this.ref = a;
  }
}
class Test<T>  {
  public <V>  void  m1(MyBag<V>  a, MyBag<V>  b, T  c)  {
  
  }
}

使用泛型方法

要傳遞方法的形式類型參數的實際類型參數,我們必須在方法調用中的點和方法名之間的尖括號<>中指定它。

class MyBag<T> {
  private T ref;

  public MyBag(T ref) {
    this.ref = ref;
  }

  public T get() {
    return ref;
  }

  public void set(T a) {
    this.ref = a;
  }
}
class Test<T> {
  public <V> void m1(MyBag<V> a, MyBag<V> b, T c) {
  }
}
public class Main {

  public static void main(String[] argv) {
    Test<String> t = new Test<String>();
    MyBag<Integer> iw1 = new MyBag<Integer>(new Integer(201));
    MyBag<Integer> iw2 = new MyBag<Integer>(new Integer(202));

    // Specify that Integer is the actual type for the type parameter for m1()
    t.<Integer>m1(iw1, iw2, "hello");

    t.m1(iw1, iw2, "hello");
  }
}

例2

以下代碼顯示了如何聲明泛型靜態(tài)方法。

我們不能在靜態(tài)方法內引用包含類的類型參數。

靜態(tài)方法只能引用它自己聲明的類型參數。

以下靜態(tài)通用類型定義了類型參數T,用于約束參數source和dest的類型。

class MyBag<T> {
  private T ref;

  public MyBag(T ref) {
    this.ref = ref;
  }

  public T get() {
    return ref;
  }

  public void set(T a) {
    this.ref = a;
  }
}

public class Main {
  public static <T> void copy(MyBag<T> source, MyBag<? super T> dest) {
    T value = source.get();
    dest.set(value);
  }

  public static void main(String[] argv) {
  }
}

要為靜態(tài)方法調用指定實際的類型參數,我們可以這樣做:

Main.<Integer>copy(iw1, iw2);

泛型構造函數

我們可以為構造函數定義類型參數。

下面的代碼定義了類Test的構造函數的類型參數U.

它放置一個約束,即構造函數的類型參數U必須是相同的,或者它的類類型參數T的實際類型的子類型。

public class Test<T> {
  public <U extends T> Test(U k) {
  }
}

要為構造函數指定實際的類型參數值,請在新運算符和構造函數名稱之間的尖括號中指定它,如以下代碼段所示:

class Test<T> {
  public <U extends T> Test(U k) {
  }
}

public class Main {
  public static void main(String[] argv) {
    // Specify the actual type parameter for the constructor as Double
    Test<Number> t1 = new<Double> Test<Number>(new Double(1.9));

    // Let the compiler figure out, Integer is
    // the actual type parameter for the constructor
    Test<Number> t2 = new Test<Number>(new Integer(1));

  }
}

泛型對象創(chuàng)建中的類型推斷

Java 7在泛型類型的對象創(chuàng)建表達式中增加了對類型推斷的有限支持。

對于以下語句:

List<String> list = new ArrayList<String>();

在Java 7中,可以在上面的語句中指定空尖括號,稱為菱形操作符或簡單的菱形<>作為ArrayList的類型參數。

List<String> list = new ArrayList<>(); 

如果我們不在對象創(chuàng)建表達式中為泛型類型指定類型參數,那么類型是原始類型,編譯器生成未檢查的警告。

例如,以下語句將編譯未選中的警告:

List<String> list = new ArrayList(); // Generates an  unchecked  warning

我們不能創(chuàng)建泛型的異常類。并且沒有泛型的匿名類。

以上內容是否對您有幫助:
在線筆記
App下載
App下載

掃描二維碼

下載編程獅App

公眾號
微信公眾號

編程獅公眾號