-1

I am new to Java. I have a HashSet of String and I am trying to convert the contains into a String[]. I follow the solution here Converting from HashSet<String> to String[] But still got error. Here is my code:

Set set = new HashSet<String>();
// Add elements into set
// ...
String[] words = set.toArray(new String[set.size()]);

The error I got is "incompatible types: java.lang.Object[] cannot be converted to java.lang.String[]"

2
  • 4
    Why are you not declaring the set initially to be a String Set?: Set<String> e.g., Set<String> set = new HashSet<>(); Commented Jan 17, 2016 at 2:23
  • @ZigZagZebra Don't mix raw types and generics. Commented Jan 17, 2016 at 2:28

1 Answer 1

2

Use the obvious solution: Just make it a generic Set<String>.

Set<String> set = new HashSet<>();
Sign up to request clarification or add additional context in comments.

2 Comments

can you tell me why casting set.toArray() to (String[]) isn't acceptable I deleted mine that said that because it got downvoted
@JRowan: the OP is already using generics but incompletely, and if you cast you lose the main reason for using generics -- you lose compile-time type checking. So if you're already using generics, the better answer is to use them correctly, not to cast.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.