AKI*_*WEB 1 java classcastexception
我试图从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())]);
}
}
Run Code Online (Sandbox Code Playgroud)
以下是我得到的例外 -
java.lang.ClassCastException: [Ljava.lang.Object; incompatible with [Ljava.lang.String;
谁可以帮我这个事?还有更好的方法吗?
ass*_*ias 11
试试这个:
String[] setArray = userIdsSet.toArray(new String[userIdsSet.size()]);
Run Code Online (Sandbox Code Playgroud)
toArray不带参数的方法返回一个Object[]不能转换为a的方法String[].在其他版本返回一个类型数组.
| 归档时间: |
|
| 查看次数: |
14829 次 |
| 最近记录: |