How to create a sorted set from the contents of an array
Hello people,
I need to write a public class method that has an array of integers as its argument and returns a sorted
set containing all of the elements of that array.
Im really stuck on this but my best attempt is as follows but this returns errors already when i Try to compile.
Code :
public SortedSet arrayToSortedSet(Integer[] anArray)
{
Set<Integer>aSet =new TreeSet<Integer>();
aSet.add(anArray);
return aSet;
}
Sorry this is such a noob question but I just cant work out how to do it.
Re: How to create a sorted set from the contents of an array
Well, this works, although there may be a more elegant solution.
Array is not a Collection, so you cannot use TreeSet's "addAll" or constructor to include elements. Sorry... you'll have to loop the good old-fashioned way, adding one element at a time.
Next, aSet must be declared to be of type SortedSet or TreeSet. Set won't work because you need to return a SortedSet
and SortedSet is a subclass of Set. So yeah, the following code should work...
Code :
public SortedSet arrayToSortedSet(Integer[] anArray)
{
SortedSet<Integer>aSet = new TreeSet<Integer>();
for(int i = 0; i < anArray.length; i++)
aSet.add(anArray[i]);
return aSet;
}
A perhaps more elegant solution is to find some type of collection that will allow you to convert arrays, and then use that collection with the treeset. Personally, I think this is alright.