0

I was reading this documentation on Java Collections and decided to test the two methods of NavigableSet Interface as follows. As the doc says for descendingSet() that The returned "view" is backed by the original NavigableSet, so changes to the descending set are also reflected in the original set. . Upon testing both the methods, I didn't see any changes in original set using descendingSet() method. Please explain why?

import java.util.Iterator;
import java.util.NavigableSet;
import java.util.TreeSet;

public class NavigableSetLearning {

    public static void main(String[] args) {

        NavigableSet<String> original = new TreeSet<String>();
        original.add("1");
        original.add("2");
        original.add("3");
        original.add("4");
        //Usage of Descending Set Method
        NavigableSet reverse = original.descendingSet();
        System.out.println(original);
        System.out.println(reverse);
        System.out.println(original);

        // Usage of Descending Iterator Method

        /*Iterator it = original.iterator();

        while(it.hasNext()){
            System.out.print("Original"+it.next()+"\n");

        }

        Iterator reverse = original.descendingIterator();
        //System.out.println(original);
        while(reverse.hasNext()){
        System.out.println("Reversed"+reverse.next()+",");
        }

        Iterator itAgain = original.iterator();

        while(itAgain.hasNext()){
            System.out.println("Original Again"+itAgain.next()+",");

        }
        */


    }

}

The output I am getting is as follows:

[1, 2, 3, 4]
[4, 3, 2, 1]
[1, 2, 3, 4] // Was expecting change here as per the doc
1

1 Answer 1

3

It means that if you remove or add elements to the reversed set derived from original, modifications to the set content will be reflected in the first set; it's an alternate view of the same set.

The ordering specified for each set will not be violated as elements are removed or added, or when descendingSet() is called.

4
  • I was thinking that after running reverse, if I run the original set, I should be getting the reverse elements as the original ordering gets disturbed.
    – John
    Oct 25, 2015 at 5:26
  • No. That would break the contract of a TreeSet, which presents elements in the order specified at construction time.
    – erickson
    Oct 25, 2015 at 5:27
  • 1
    I see. I tried to add 5 as reverse.add("5") and the ordering was preserved like 5,4,3,2,1.
    – John
    Oct 25, 2015 at 5:29
  • And we can't do anything like we did above with descendentIterator() method, right?
    – John
    Oct 25, 2015 at 6:12

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.