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),表示未知型別。您可以將萬用字元用作:
- 引數型別。
- 欄位
- 區域性欄位。
上界萬用字元
萬用字元中的上界類似於泛型中的有界型別。使用它,您可以啟用將特定類的所有子型別用作型別引數。
例如,如果要將Collection物件作為方法的引數,其型別引數為Number類的子類,您只需要宣告一個以Number類為上界的萬用字元。
要建立/宣告上界萬用字元,您只需要在“?”後指定extends關鍵字,後跟類名。
示例
以下Java示例演示了上界萬用字元的建立。
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.List;
import java.util.HashSet;
public class UpperBoundExample {
public static void sampleMethod(Collection<? extends Number> col){
for (Number num: col) {
System.out.print(num+" ");
}
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<Float> 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);
}
}輸出
24 56 89 75 36 22.1 3.32 51.4 82.7 95.4 625.0 25.225 554.32 2254.22 445.21
如果將除Number子類型別的集合物件以外的引數傳遞給上述程式的sampleMethod(),則會生成編譯時錯誤。
示例
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.List;
import java.util.HashSet;
public class UpperBoundExample {
public static void sampleMethod(Collection<? extends Number> col){
for (Number num: col) {
System.out.print(num+" ");
}
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<Float> col2 = Arrays.asList(22.1f, 3.32f, 51.4f, 82.7f, 95.4f, 625.f);
sampleMethod(col2);
HashSet<String> col3 = new HashSet<String>();
col3.add("Raju");
col3.add("Ramu");
col3.add("Raghu");
col3.add("Radha");
sampleMethod(col3);
}
}編譯時錯誤
UpperBoundExample.java:31: error: incompatible types: HashSet<String> cannot be converted to Collection<? extends Number> sampleMethod(col3); ^ Note: Some messages have been simplified; recompile with -Xdiags:verbose to get full output 1 error
廣告
資料結構
網路
關係資料庫管理系統 (RDBMS)
作業系統
Java
iOS
HTML
CSS
Android
Python
C語言程式設計
C++
C#
MongoDB
MySQL
Javascript
PHP