[英]Generic method in java not returning the type expected
I have created a generic method toList(): 我创建了一个通用方法toList():
public static <T> List<T> toList(T... args){
List<T> list = new ArrayList<T>();
for (T t : args) {
list.add(t);
}
if(list instanceof Comparable<?>){
System.out.println("The list was considered a list of Comparable objects");
}
if(list instanceof Serializable){
System.out.println("The list was considered a list of Serializable objects");
}
if(list instanceof Object){
System.out.println("The list was considered a list of Object class' objects");
}
return list;
}
I am calling this method like : 我正在像这样调用此方法:
public static void main(String[] args) {
System.out.println(Generics.<Comparable>toList(1,2,"3"));
}
I was expecting that since I have supplied the type Comparable, the first if condition would hold true and o/p would be first Comparable, then Object. 我期待着因为我已经提供了Comparable类型,所以第一个if条件将为true,而o / p将首先为Comparable,然后是Object。 But to my surprise, control didn't go in first if and the o/p was Serializable and then Object.
但是令我惊讶的是,如果并且o / p是Serializable然后是Object,则控件没有首先进入。
Can anyone throw some light on the reason behind this? 任何人都可以阐明其背后的原因吗? Also I am not clear with the concept of applying T in the method signature after the access modifier.
我也不清楚在访问修饰符之后在方法签名中应用T的概念。
We have mentioned the access specifier, modifier and the return type. 我们已经提到了访问说明符,修饰符和返回类型。 What is the need of supplying T ?
供应T有什么需要?
You are performing your assertions on the list object and not on the elements of the list. 您正在对列表对象而不是对列表元素执行断言。
list instanceof Comparable<?>
This will only return true
if the list itself would implement the Comparable
interface. 仅当列表本身将实现
Comparable
接口时,才返回true
。 As ArrayList
is serializable and of course is an object the other two conditions will evaluate to true
. 由于
ArrayList
是可序列化的,并且当然是对象,因此其他两个条件的评估结果为true
。
It seems to me what you are trying to do is test the element type, T
, inside your method. 在我看来,您要尝试的是测试方法内部的元素类型
T
Because of type erasure (follow the link) you cannot do this. 由于类型擦除(遵循链接),您无法执行此操作。 The actual type of
T
is only known at compile time, not on runtime. T
的实际类型仅在编译时才知道,而在运行时则不知道。 On runtime, inside the method, Java will just think T
is Object
. 在运行时,在方法内部,Java只会认为
T
是Object
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.