java.lang.ClassCastException: [Ljava.lang.Object; 与 [Ljava.lang.String; 不兼容;

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/17201725/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-11-01 01:18:16  来源:igfitidea点击:

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

javaclasscastexception

提问by AKIWEB

I am trying to retrieve random elements from a linkedhashset. Below is my code but it is giving me exception everytime.

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

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())]);
    }
}

Below is the exception I am getting-

以下是我得到的例外-

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

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

Can anyone help me on this? And is there any better way of doing this?

谁可以帮我这个事?有没有更好的方法来做到这一点?

回答by assylias

Try this:

试试这个:

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

the toArraymethod that takes no argumentsreturns an Object[]which can't be cast to a String[]. The other versionreturns a typed array.

toArray不带参数方法返回Object[]无法转换为 a 的String[]。在其他版本返回一个类型数组。