[英]Can Generic Class be method/return type?
I am Currently learning Generics I have this Generic class here 我目前正在学习泛型我在这里有这个泛型课程
package generics.lesson;
public class Pair<T> {
private T first;
private T second;
public Pair(){ first = null; second = null; }
public Pair(T first, T second){ this.first = first ; this.second = second;}
public T getFirst() { return first; }
public T getSecond() { return second; }
public void setFirst(T first) { this.first = first; }
public void setSecond(T second) { this.second = second; }
}
So far I understand this but then I came across this 到目前为止,我理解了这一点,但是后来我发现了这一点
public static Pair<String> minmax(String[] a)
{
if(a.length == 0 || a == null) return null;
String min = a[0];
String max = a[0];
for(int i = 1 ; i < a.length ; i++)
{
if(min.compareTo(a[i])>0) min = a[i];
if(max.compareTo(a[i])<0) max = a[i];
}
return new Pair<String>(min,max);
}
What confuses me is this 令我困惑的是
public static Pair<String> minmax(String[] a)
QUestion 题
How is this possible? 这怎么可能? and can a generic class be a method return type? 泛型类可以是方法的返回类型吗?
Yes, it can. 是的,它可以。
Why would you think it can't? 您为什么认为不能呢?
If this works 如果这可行
public T getFirst() { return first; } // returns a generic type
public T getSecond() { return second; } // returns a generic type
(which you said you "understand this") (您说过您“了解这一点”)
I would expect this to also work 我希望这也会起作用
public static Pair<String> minmax(String[] a) // returns a generic type
BTW: In Java 1.4 neither works, In Java 5.0+ both work. 顺便说一句:在Java 1.4中都不起作用,在Java 5.0+中都起作用。 ;) ;)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.