您能解释一下Java中装箱和泛型的奇怪行为吗
根据以下规则,以下代码应该会导致编译错误:您能解释一下Java中装箱和泛型的奇怪行为吗,java,generics,Java,Generics,根据以下规则,以下代码应该会导致编译错误: import java.util.*; public class GenericTest1 { // Add T-array of objects to collection<T> static <T> void fromArrayToCollection(T[] a, Collection<T> c) { for (T o : a) { c.add(o);
import java.util.*;
public class GenericTest1 {
// Add T-array of objects to collection<T>
static <T> void fromArrayToCollection(T[] a, Collection<T> c) {
for (T o : a) {
c.add(o);
}
}
public static void main( String[] args ) {
Number[] na = new Number[100];
Collection<Number> cn = new ArrayList<Number>();
// This should work and does
fromArrayToCollection( na, cn );
Collection<String> cs = new ArrayList<String>();
// This should fail to copile and does
fromArrayToCollection( na, cs );
}
}
有人能解释为什么吗 它之所以有效,是因为
one
(Number
)和“one”
(String
)都是对象,就像1
(Integer
到期)和“one”
(String
)一样。因此,T
被计算为对象
,调用equals并返回false
。
它不适用于集合
(以及其他泛型)在您的第二次测试中,1
将被简单地装箱到一个整数
实例中,该实例也是对象
的一个实例
自动装箱的结果是,此处的1
将转换为整数(1)
,这是一个对象。String(“One”)
和Integer(1)
都继承了.equals
来自Object
的函数,因此它可以无错误地编译。谢谢!和链接。
GenericTest1.java:25: error: method fromArrayToCollection in class GenericTest1 cannot be applied to given types;
fromArrayToCollection( na, cs );
^
required: T[],Collection<T>
found: Number[],Collection<String>
reason: inference variable T has incompatible bounds
equality constraints: String
lower bounds: Number
where T is a type-variable:
T extends Object declared in method <T>fromArrayToCollection(T[],Collection<T>)
public class GenericTest2 {
// Test for equality of two objects of type T
static <T> boolean testEquality(T first, T second ) {
return first.equals( second );
}
public static void main( String[] args ) {
// Should work
System.out.println( testEquality( "One", "One" ) );
// Shouldn't this refuse to compile ?
System.out.println( testEquality( "One", 1 ) );
// Shouldn't this refuse to compile ?
Number one = new Integer( 1 );
System.out.println( testEquality( "One", one ) );
}
}
true
false
false