我已经看到了类似的方法如下所示:<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 –