Java泛型方法中什麼是下界萬用字元?
泛型是Java中一個概念,您可以透過它使類、介面和方法能夠接受所有(引用)型別作為引數。換句話說,它是一個允許使用者動態選擇方法、類建構函式接受的引用型別的概念。透過將類定義為泛型,您使其型別安全,即它可以作用於任何資料型別。
要定義泛型類,您需要在類名後面的尖括號“<>”中指定要使用的型別引數,您可以將其視為例項變數的資料型別並繼續編寫程式碼。
示例
class Student<T>{
T age;
Student(T age){
this.age = age;
}
public void display() {
System.out.println("Value: "+this.age);
}
}
public class GenericsExample {
public static void main(String args[]) {
Student<Float> std1 = new Student<Float>(25.5f);
std1.display();
Student<String> std2 = new Student<String>("25");
std2.display();
Student<Integer> std3 = new Student<Integer>(25);
std3.display();
}
}輸出
Value: 25.5 Value: 25 Value: 25
萬用字元
除了泛型中的型別引數(T)之外,您還可以使用“?”來表示未知型別。您可以將萬用字元用作:
- 引數型別。
- 欄位。
- 區域性欄位。
萬用字元的唯一限制是,在呼叫泛型方法時,不能將其用作泛型方法的型別引數。
Java 提供了三種類型的萬用字元,即上界萬用字元、下界萬用字元和無界萬用字元。
下界萬用字元
上界萬用字元允許將特定類的所有子型別用作型別引數。
類似地,如果我們使用下界萬用字元,則可以將“?”的型別限制為特定型別或其超型別。
例如,如果要將 Collection 物件作為方法的引數,並且型別引數為 Integer 類的超類,則只需宣告一個以 Integer 類作為下界的萬用字元。
要建立/宣告下界萬用字元,只需在“?”後指定 super 關鍵字,然後是類名。
示例
以下 Java 示例演示瞭如何建立下界萬用字元。
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.List;
import java.util.Iterator;
public class LowerBoundExample {
public static void sampleMethod(Collection<? super Integer> col){
Iterator it = col.iterator();
while (it.hasNext()) {
System.out.print(it.next()+" ");
}
System.out.println("");
}
public static void main(String args[]) {
ArrayList<Integer> col1 = new ArrayList<Integer>();
col1.add(24);
col1.add(56);
col1.add(89);
col1.add(75);
col1.add(36);
sampleMethod(col1);
List<Object> col2 = Arrays.asList(22.1f, 3.32f, 51.4f, 82.7f, 95.4f, 625.f);
sampleMethod(col2);
}
}輸出
24 56 89 75 36 22.1 3.32 51.4 82.7 95.4 625.0
如果將型別不是 Integer 及其超型別的 Collection 物件作為上述程式中 sampleMethod() 的引數傳遞,則會生成編譯時錯誤。
示例
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.List;
import java.util.Iterator;
import java.util.HashSet;
public class LowerBoundExample {
public static void sampleMethod(Collection<? super Integer> col){
Iterator it = col.iterator();
while (it.hasNext()) {
System.out.print(it.next()+" ");
}
System.out.println("");
}
public static void main(String args[]) {
ArrayList<Integer> col1 = new ArrayList<Integer>();
col1.add(24);
col1.add(56);
col1.add(89);
col1.add(75);
col1.add(36);
sampleMethod(col1);
List<Object> col2 = Arrays.asList(22.1f, 3.32f, 51.4f, 82.7f, 95.4f, 625.f);
sampleMethod(col2);
HashSet<Double> col3 = new HashSet<Double>();
col3.add(25.225d);
col3.add(554.32d);
col3.add(2254.22d);
col3.add(445.21d);
sampleMethod(col3);
}
}編譯時錯誤
LowerBoundExample.java:34: error: incompatible types: HashSet<Double> cannot be converted to Collection<? super Integer> sampleMethod(col3); ^ Note: Some messages have been simplified; recompile with -Xdiags:verbose to get full output 1 error
廣告
資料結構
網路
關係型資料庫管理系統
作業系統
Java
iOS
HTML
CSS
Android
Python
C語言程式設計
C++
C#
MongoDB
MySQL
Javascript
PHP