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

标签 java generics

根据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/

相关文章:

c# - JSON反序列化器继承泛型类型

ios - 无法推断通用参数

python - 如何参数化通用 Python 模块?

java - 通过Collections类的算法获取集合的 “dynamically typesafe view”

java - Android Studio 不显示 java 类源

java - 为什么当我改变场景时随机边界的值会重置?

java - ContentProviderOperations 和传统插入的优点和缺点

java - 未对以编程方式创建的 UI 元素执行 JSF 2.0 支持 bean 方法

java - 为什么我们不能捕获具有两个参数的方法的通配符?

java - 通过 JNA 调用 native C++ 函数的非确定性返回值(字符串类型)