gpt4 book ai didi

java - 你能解释一下 Java 中装箱和泛型的奇怪行为吗

转载 作者:行者123 更新时间:2023-11-29 05:05:13 25 4
gpt4 key购买 nike

根据Java docs以下代码应该会导致编译错误:

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 );
}
}

确实如此:

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

谁能解释一下为什么?

最佳答案

之所以有效,是因为 one ( Number ) 和 "One" ( String ) 都是 Object s,和1一样( Integer 由于 autoboxing )和 "One" (String)。所以T被评估为 Object , equals 被调用并返回 false .它不适用于 Collection (以及与此相关的其他泛型)because a Collection<String> can not be cast to a Collection<Object>

关于java - 你能解释一下 Java 中装箱和泛型的奇怪行为吗,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30590034/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com