Hi I am having trouble understanding why the output is 'ex [6, 7, b, d] [6, 7, b]' for this piece of code. Please can someone advise how the subset is working with the numbers and letters? thanks
import java.util.*;
public class Corner {
public static void main(String[] args) {
TreeSet<String> t1 = new TreeSet<String>();
TreeSet<String> t2 = new TreeSet<String>();
t1.add("b"); t1.add("7");
t2 = (TreeSet)t1.subSet("5", "c");
try {
t1.add("d");
t2.add("6");
t2.add("3");
}
catch (Exception e) { System.out.print("ex "); }
System.out.println(t1 + " " + t2);
} }
I have made a few changes to clean up your code (usage of raw generic type and unchecked conversion) and to make the log output somewhat more insightful:
The output looks like this:
Okay, after insertion of "b" and "7", t1 contains those elements in ASCII (or Unicode) sort order. t2 is empty. No surprise here.
After the
subSet
call, both sets have identical content because the given range "5" to "c" spans the whole current range of the original set from "7" to "b". No surprise either.Please note: The subset is backed by the original set as described by the API JavaDoc.
Furthermore the API description says that the returned set will throw an
IllegalArgumentException
on an attempt to insert an element outside its range. This will be important later on.Okay, next you add element "d" to t1 which is shown in t1, but not in t2 because "d" is outside the range "5" to "c" of t2.
Now you add element "6" to t2 (which is still backed by t1!). It is in the correct range of t2 and thus successfully added to both logical sets.
Now you run into trouble because you try to add "3" to t2, which is out of range "5" to "c", thus causing the
IllegalArgumentException
which can be seen in the log output. The element is not inserted into t2 (and thus not into t1 either). Consequently it is not shown in the last line of log output.Bottom line: Your program behaves just as expected according to the JDK documentation.
:-)