首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >你能用Java解释Boxing和Generics的奇怪行为吗?

你能用Java解释Boxing和Generics的奇怪行为吗?
EN

Stack Overflow用户
提问于 2015-06-02 07:33:56
回答 3查看 65关注 0票数 1

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

代码语言:javascript
复制
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 );
   }
}

它确实做到了:

代码语言:javascript
复制
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>)

然而,这是编译和运行完美的。

代码语言:javascript
复制
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 ) );

   }
}

产出如下:

代码语言:javascript
复制
true
false
false

有人能解释原因吗?

EN

回答 3

Stack Overflow用户

回答已采纳

发布于 2015-06-02 07:37:10

这是因为one(Number)和"One"(String)都是Object的,1(由于自动拳击引起的Integer)和"One"(String)也是如此。因此,T被求值为Object,等于获得调用并返回false。它不适用于Collection(以及其他泛型) Collection

票数 2
EN

Stack Overflow用户

发布于 2015-06-02 07:42:30

testEquality( "One", 1 )

作为自动装箱的结果,这里的1将被转换为Integer(1),这是一个对象。String("One")Integer(1)都继承了Object.equals函数,因此可以编译而不出错。

票数 1
EN

Stack Overflow用户

发布于 2015-06-02 07:38:50

在第二个测试中,1将被简单地装箱到一个Integer实例中,该实例也是Object的一个实例。

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/30590034

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档