我已經看到了類似的方法如下所示:<T擴展是什麼意思?
protected <T extends ABC> T save(T Acd, boolean en) {
它有什麼作用?在Java中調用的這些類型的方法聲明是什麼?
我已經看到了類似的方法如下所示:<T擴展是什麼意思?
protected <T extends ABC> T save(T Acd, boolean en) {
它有什麼作用?在Java中調用的這些類型的方法聲明是什麼?
這就是所謂的通用方法。這個整體概念在Java中被稱爲「泛型」。該聲明意味着T可以是ABC的任何類型的子類。
我可以使用任何字母表嗎?或者只有T是唯一的聲明類型,提及它是一種通用方法? –
您可以使用任何字母。 T是我認爲的「類型」的縮寫。在地圖結構中使用
您可以對通用類型參數使用任何合法標識符,但約定表明它應該是大寫字母。看到這個答案:http://stackoverflow.com/questions/2900881/generic-type-parameter-naming-convention-for-java-with-multiple-chars。使用一個單詞通常是一個糟糕的主意,因爲當你閱讀類似「List
這意味着你必須發送一個ABC
對象或ABC
的孩子,沒有其他類允許。另外,您的Acd
變量可以使用ABC
類中的方法,這些方法對於與方法相關的類可見。
當您的T
類擴展接口時,這非常有用。例如,你要創建一個處理對象數組排序和這個類必須實現 TNE Comparable
接口的類,否則數組將不會被允許:
class Class1 implements Comparable<Class1> {
//attributes, getters and setters...
int x;
//implementing the interface...
public int compareTo(Class1 c1) {
//nice implementation of compareTo
return (this.x > c1.x)? 1 : (this.x < c1.x) ? 0 : -1;
}
}
class Class2 {
int x;
}
public class Sorter<T extends Comparable<T>> {
public static void insertionSort(T[] array) {
//good implementation of insertion sort goes here...
//just to prove that you can use the methods of the Comparable interface...
array[0].compareTo(array[1]);
}
public static void main(String[] args) {
Class1[] arrC1 = new Class1[5];
Class2[] arrC2 = new Class2[5];
//fill the arrays...
insertionSort(arrC1); //good!
insertionSort(arrC2); //compiler error!
}
}
這是仿製藥。類型邊界的泛型!
限制類型參數:
有可能是當你要限制各種被允許傳遞到一個類型參數的類型。例如,對數字進行操作的方法可能只想接受Number或其子類的實例。這是有界類型參數的用途。
要聲明一個有界的類型參數,請列出類型參數的名稱,後跟extends關鍵字,後跟其上限。 示例:
下面的例子說明了擴展在一般意義上是如何用來表示「擴展」(如在類中)或「實現」(如在接口中)。這個例子是返回最大的三個比較的對象的一般方法:
public class MaximumTest
{
// determines the largest of three Comparable objects
public static <T extends Comparable<T>> T maximum(T x, T y, T z)
{
T max = x; // assume x is initially the largest
if (y.compareTo(max) > 0){
max = y; // y is the largest so far
}
if (z.compareTo(max) > 0){
max = z; // z is the largest now
}
return max; // returns the largest object
}
public static void main(String args[])
{
System.out.printf("Max of %d, %d and %d is %d\n\n",
3, 4, 5, maximum(3, 4, 5));
System.out.printf("Maxm of %.1f,%.1f and %.1f is %.1f\n\n",
6.6, 8.8, 7.7, maximum(6.6, 8.8, 7.7));
System.out.printf("Max of %s, %s and %s is %s\n","pear",
"apple", "orange", maximum("pear", "apple", "orange"));
}
}
這是Java泛型叫。
官方解釋:簡而言之,泛型在定義類,接口和方法時使類型(類和接口)成爲參數。就像方法聲明中使用的更熟悉的形式參數一樣,類型參數爲您提供了一種方法,讓您可以在不同的輸入中重用相同的代碼。區別在於形式參數的輸入是值,而類型參數的輸入是類型。
非正式:Java等強類型語言會導致在編譯時顯示更多錯誤,而不是運行時。這是一件好事。但它會導致代碼重複。爲了減輕這種泛型被添加到Java。
閱讀一些教程。您可以從以下開始: - http://docs.oracle.com/javase/tutorial/extra/generics/index.html –
我不覺得它是如何調用一個構造的問題!+1 –