1

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?

1
  • You should convert your array using userIdsSet.toArray(new String[]) to generate a String array. Otherwise the method you are using will generate an Object array. Commented Jun 19, 2013 at 21:33

1 Answer 1

11

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.

4
  • @assylias Good point! In the link you provided they use new String[0]... I tested it and it works as well as your example Commented Jun 19, 2013 at 21:50
  • 1
    @Paolof76 using new String[0] allocates an unnecessary object so I prefer the version in my answer where possible (although the difference is minimal in most situations). Commented Jun 19, 2013 at 21:51
  • @assylias why it is different from new String[userIdsSet.size()]? Commented Jun 19, 2013 at 21:54
  • 2
    @Paolof76 if you use set.toArray(new String[0]), you create an empty array (new String[0]) and the toArray method will create an array of the right size. If you use set.toArray(new String[set.size()]);, the toArray method uses your array and returns it, so only one array is created. Commented Jun 19, 2013 at 22:00

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.