Reputation: 915
I have started implementing a TreeSet
in java
.
i wish to knows, is it possible to create a set within a set.
For example i need to create a set that gives output
{{1,2,3,4,5,6,7,8},(1,{1,2,3,4,5,6,7,8})}
The problem is that i can't get add to my sets to give the desired output.
I have even tried putting my treeset
within an arraylist
.
ArrayList<TreeSet<Integer>> SET = new ArrayList<TreeSet<Integer>>();
this still doesn't give me my desired result, and makes my code really complicated.
as you can see, the output has 2 sets that are basically elements of a larger set.
Please can anyone help?
I AM NOT ASKING FOR CODE ONLY ADVICE!!!
Upvotes: 1
Views: 410
Reputation: 727077
TreeSet<T>
needs a comparator on T
in order to arrange the elements inside it. You can cerate a TreeSet
with a custom comparator that "understands" how to compare TreeSet
s. This will let the outer tree set decide on the order of the tree sets that you put inside it:
TreeSet<TreeSet<Integer>> outer = new TreeSet<TreeSet<Integer>>(
new Comparator<TreeSet<Integer>>() {
public int compare(TreeSet<Integer> lhs, TreeSet<Integer> rhs) {
Iterator<Integer> li = lhs.Iterator();
Iterator<Integer> ri = rhs.Iterator();
while (li.hasNext() && ri.hasNext()) {
int res = li.next().compareTo(ri.next());
if (res != 0) return res;
}
if (li.hasNext()) return 1;
if (ri.hasNext()) return -1;
return 0;
}
}
);
Upvotes: 1
Reputation: 5848
Your use of Generics is confusing you.
This: ArrayList<TreeSet<Integer>> SET = new ArrayList<TreeSet<Integer>>();
Doesn't put a list in a list.
To do that you need to do this:
TreeSet s = new TreeSet();
TreeSet subset = new TreeSet();
s.add(subset);
Upvotes: 0