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;
Can anyone help me on this? And is there any better way of doing this?
Try this:
String[] setArray = userIdsSet.toArray(new String[userIdsSet.size()]);
the toArray
method that takes no arguments returns an Object[]
which can't be cast to a String[]
. The other version returns a typed array.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.