If you really need to add array list (as an instance) and not its elements, you should use another constructor rather than the empty one, consider the constructor taking as a parameter a Comparator.
TreeSet(Comparator<? super E> comparator)
Constructs a new, empty tree set, sorted according to the specified comparator.
You can define upfront a Comparator for your purpose with the meaning you actually want with regards to the concerned arraylists.
Then add the array list instances, which will properly compared according to your comparator.
As an example, you can define a Comparator which would compare array lists based on their size (sample simple comparison):
public class MyArrayListComparator implements java.util.Comparator<ArrayList> {
public int compare(ArrayList al1, ArrayList al2) {
if (al1.size() > al2.size())
return 1;
if (al1.size() < al2.size())
return -1;
return 0;
}
}
Then in your code:
ArrayList al = new ArrayList();
ArrayList al2 = new ArrayList();
ArrayList al3 = new ArrayList();
TreeSet ts = new TreeSet(new MyArrayListComparator());
ts.add(al);
ts.add(al2);
ts.add(al3);
Note the
TreeSet ts = new TreeSet(new MyArrayListComparator());
This is actually a good example of the difference between Comparable and Comparator:
- Comparable is implemented by the class you want to use, with a specific behavior and you cannot change it or add it
- Comparator is an external implementation you can add (if supported by the concerned consumer) with the behavior you want
Check also this SO Q/A for further details on Comparable vs Comparator.