-1

I'm trying to convert my set of Strings to an array of Strings so I can operate on them one by one. Is there a better way of doing this or is converting to arrays a good way? However, when I try converting to an array like below then I get errors as it doesn't think that it will always be strings passed in. Would appreciate some pointers.

Set<String> s;

s.add("a");
s.add("b");
String[] item =  s.toArray();
Alex
  • 627
  • 3
  • 12
  • 32
  • The reason you get errors is because `toArray` with no arguments returns an `Object[]`. You need to give it an argument, even a dummy argument like `new String[0]`, in order to get it to return an array of something else. See the javadoc [here](http://docs.oracle.com/javase/7/docs/api/java/util/Set.html#toArray(T[])). – ajb Feb 08 '14 at 01:07

3 Answers3

2

You do not have to convert a Set to an array just to operate on the elements. You can iterate over the elements directly

Set<String> s = new HashSet<>();
....
for (String item : s)
{
    do something...
}
Jim Garrison
  • 85,615
  • 20
  • 155
  • 190
1
so I can operate on them one by one

You don't have to convert it to an array for that.

Instead iterate using the for-each loop or the iterator.

Ajay George
  • 11,759
  • 1
  • 40
  • 48
0

you can do something like this

String[] item = s.toArray(new String[s.size()]);

As per Java doc - toArray function ( which is the one you need )

toArray() Returns an array containing all of the elements in this list in proper sequence (from first to last element).

Maciej Cygan
  • 5,351
  • 5
  • 38
  • 72