【问题标题】:Strange behaviour, Generic ArrayList of Long奇怪的行为,长的通用 ArrayList
【发布时间】:2012-08-26 19:33:15
【问题描述】:

我有someMethod(),它返回Collection<Long>

ArrayList<Long> results = (ArrayList<Long>) someMethod();
Long value = results.get(0);

我收到ClassCastException: java.util.ArrayList cannot be cast to java.lang.Long。 尝试System.out.println(results.get(0)); 实际上,它返回例如[32]。 我不明白。这是长的 ArrayList!为什么get(0) 返回ArrayList

这有帮助:

Object o = results.get(0);
ArrayList<Long> al = (ArrayList<Long>) o;
Long val = al.get(0);

但为什么需要这样做?

【问题讨论】:

  • someMethod 返回Collection&lt;ArrayList&lt;Long&gt;&gt;"[ 32 ]" 等价于 ArrayList.toString()ArrayList 仅包含 32
  • 能看到someMethod的签名吗?
  • Collection&lt;Long&gt; someMethod(Collection&lt;? extends SomeInterface&gt; target)

标签: java generics arraylist


【解决方案1】:

显然someMethod() 实际上返回Collection&lt;List&lt;Long&gt;&gt;,违反了声明的返回类型。由于类型擦除,这是可能的。只要类类型正确,编译器就会高兴,泛型类型可以忽略(编译器只会发出警告)。基本上这是someMethod() 中的一个错误。

【讨论】:

    猜你喜欢
    • 2013-10-11
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-04-29
    • 1970-01-01
    • 2018-07-05
    相关资源
    最近更新 更多