0

I have a Set that contains different random lines from a text file, now I'm new to Java so I don't know much about the methods available but I have tried using the java.util.Set.toArray() method but it returns an Object[] than can not be sorted.

Is there anyway to do this? any help would be appreciated.

Thank you.

3
Contributors
2
Replies
3
Views
8 Years
Discussion Span
Last Post by quuba
0

If you are developing in Java 1.5 consider using generics in which you can make toArray() of Set return an array of T[] where T is the type of element you have stored in your Set.

Set<String> s = obj.someMethod();
String[] sArr = s.toArray(new String[s.size()]);

Alternatively, you can create a TreeSet out of your given Set which guarantees that its elements are always ordered.

Set s = obj.someMethod();
s = new TreeSet(s);
// s now contains elements sorted according to their
// natural ordering

Also, if you are in control of the method which returns a Set , you can modify the logic to store the elements in a TreeSet from the start which will do away with the need of performing a sort later on i.e. sort as you add.

./sos

0
import java.util.Iterator;
import java.util.SortedSet;
import java.util.TreeSet;

public class BlackRobe {

    public static void main(String args[]) {
        SortedSet<String> set = new TreeSet<String>();
        set.add("beta");
        set.add("alfa");
        set.add("gamma");
        Iterator<String> it = set.iterator();
        while (it.hasNext()) {
            String s = it.next();
            System.out.println(s);
        }
    }
}
This topic has been dead for over six months. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.