Join the Stack Overflow Community
Stack Overflow is a community of 4.7 million programmers, just like you, helping each other.
Join them; it only takes a minute:
Sign up

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?

share|improve this question
    
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. – Edwin Dalorzo Jun 19 '13 at 21:33
up vote 11 down vote accepted

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.

share|improve this answer
    
Perhaps explain why? – T.J. Crowder Jun 19 '13 at 21:32
    
@assylias Good point! In the link you provided they use new String[0]... I tested it and it works as well as your example – Paolof76 Jun 19 '13 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). – assylias Jun 19 '13 at 21:51
    
@assylias why it is different from new String[userIdsSet.size()]? – Paolof76 Jun 19 '13 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. – assylias Jun 19 '13 at 22:00

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.