【问题标题】:java.lang.ClassCastException: [Ljava.lang.Object; incompatible with [Ljava.lang.String;java.lang.ClassCastException:[Ljava.lang.Object;与 [Ljava.lang.String; 不兼容;
【发布时间】:2013-06-19 21:30:45
【问题描述】:

我正在尝试从链接哈希集中检索随机元素。下面是我的代码,但每次都给我异常。

private static void generateRandomUserId(Set<String> userIdsSet) {

    Random rand = new Random(System.currentTimeMillis());
    String[] setArray = (String[]) userIdsSet.toArray();
    for (int i = 0; i < 10; ++i) {
        System.out.println(setArray[rand.nextInt(userIdsSet.size())]);
    }
}

以下是我得到的例外-

java.lang.ClassCastException: [Ljava.lang.Object; incompatible with [Ljava.lang.String;

谁能帮我解决这个问题?有没有更好的方法来做到这一点?

【问题讨论】:

  • 您应该使用userIdsSet.toArray(new String[]) 转换您的数组以生成一个字符串数组。否则,您使用的方法将生成一个 Object 数组。

标签: java classcastexception


【解决方案1】:

试试这个:

String[] setArray = userIdsSet.toArray(new String[userIdsSet.size()]);

toArray method that takes no arguments 返回一个不能转换为 String[]Object[]other version 返回一个类型化数组。

【讨论】:

  • @assylias 好点!在您提供的链接中,他们使用 new String[0]... 我对其进行了测试,它与您的示例一样有效
  • @Paolof76 使用new String[0] 分配了一个不必要的对象,所以我更喜欢我的答案中可能的版本(尽管在大多数情况下差异很小)。
  • @assylias 为什么它与 new String[userIdsSet.size()] 不同?
  • @Paolof76 如果你使用set.toArray(new String[0]),你会创建一个空数组(new String[0]),toArray 方法会创建一个大小合适的数组。如果你使用set.toArray(new String[set.size()]);toArray 方法使用你的数组并返回它,所以只创建一个数组。
猜你喜欢
  • 1970-01-01
  • 2017-01-11
  • 2014-05-09
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多