gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-29 09:48:43 32 4
gpt4 key购买 nike

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

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;与 [Ljava.lang.String;

不兼容

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

最佳答案

试试这个:

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

toArray method that takes no arguments返回无法转换为 String[]Object[]other version返回类型化数组。

关于java.lang.ClassCastException : [Ljava. lang.Object;不兼容 [Ljava.lang.String;,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17201725/

32 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com