【发布时间】: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 数组。