来自Cay Horstmann的Java泛型,核心Java 7,第I卷,第716页 [英] Java generics from Cay Horstmann, Core Java 7, Volume I, page 716

查看:95
本文介绍了来自Cay Horstmann的Java泛型,核心Java 7,第I卷,第716页的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在学习Java 7泛型,阅读Cay Horstmann,Core Java7,第I卷,第716页。
我不明白为什么发生运行时错误(非法转换),请参阅下面的代码。
任何人都可以比我更好地向我解释吗?

I am learning Java 7 generics, reading Cay Horstmann, Core Java7, Volume I, on page 716. I dont understand why the run time error (cast illegal) occurs, please see code below. Can anyone explain it to me better than Cay does?

public class ProcessArgs 
{

  public static <T extends Comparable> T[] minmax(T... a)
  {
    Object[] mm = new Object[2];
    mm[0] = a[0];
    mm[1] = a[1];
    if (mm[0] instanceof Comparable)
    {
        System.out.println("Comparable"); // this is True, prints Comparable at run-time
    }
    return (T[]) mm;  // run-time error here

    /* Run-Time ERROR as below:
     ComparableException in thread "main" 
     java.lang.ClassCastException: [Ljava.lang.Object; cannot be cast to [Ljava.lang.Comparable;
      at ProcessArgs.minmax(ProcessArgs.java:13)
      at ProcessArgs.main(ProcessArgs.java:18)
     */

  }

  public static void main(String[] args) 
  {
    String[] sa = minmax("Hello","World"); // ERROR, illegal cast
    System.out.println(sa[0] + sa[1]);
    Object o = "Hello World"; //works - if we comment out the method call to minmax above
    Comparable<String> s = (Comparable) o; // works
    Comparable s2 = (Comparable) o; // works
    System.out.println(s + " " + (String) s2); // works
    return;
  }
}


推荐答案

它抛出一个错误,因为你创建的实际类型 Object [] 不是 Comparable 。 Java泛型对数组的处理很差,如果可能的话,你应该尝试使用Collections。对于这种情况,您可以使用反射来创建适当类型的数组:

It throws an error because the actual type you created, Object[] is NOT a Comparable. Java generics deal pretty poorly with arrays, you should try to use Collections if possible. For this case, you can create an array of the proper type using reflection:

T[] mm = (T[]) Array.newInstance(a[0].getClass(), 2 );

鉴于以下两行:

Given these two lines:

Object o = "Hello World"; //works - if we comment out the method call to minmax above
Comparable<String> s = (Comparable) o; // works

第二行是因为字符串Hello World实际上是一个可比较

The second line works because the string "Hello World" actually is a Comparable.

Object [] 不是,它的类型是 Object [] ,所以它不能被转换。

But Object[] isn't, its type is Object[], so it can't be cast.

这篇关于来自Cay Horstmann的Java泛型,核心Java 7,第I卷,第716页的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆