Reputation: 19632
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?
Upvotes: 1
Views: 17828
Reputation: 328913
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.
Upvotes: 11