title: Internal working of Java Collections Framework
body: <p>I've had this question for a very very long time. </p>
  
  <p>Question is a bit long. Please bear with me :)</p>
  
  <p>In Summary, how does a collection datastructure such as <code>TreeSet</code> know when the underlying data it stores gets modified and how does it manage such cases??</p>
  
  <p><strong>Example</strong></p>
  
  <pre><code>//Simple person class with name data member
  public static class Person {
      String name;
  
      public Person(String name) {
          this.name = name;
      }
  }
  </code></pre>
  
  <p><br/>
  <strong>1. Create a TreeSet and add 3 Person instances p1, p2, p3. (Comparator sorts name).</strong></p>
  
  <pre><code>TreeSet&lt;Person&gt; set = new TreeSet&lt;&gt;(new Comparator&lt;Person&gt;() {
      @Override
      public int compare(Person person1, Person person2) {
          return person1.name.compareTo(person2.name);
      }
  });
  
  // Creating 3 Person instances and adding to set.
  Person p1 = new Person("Zach"),
          p2 = new Person("Henry"),
          p3 = new Person("Adam");
  
  // Adding to set
  set.add(p1);  set.add(p2);  set.add(p3);
  </code></pre>
  
  <p><br/>
  <strong>2. Printing the First Element (Prints the lexicographical smallest string in balanced BST)</strong></p>
  
  <pre><code>// This will name of P3 instance, i.e. Adam (obvious and expected) 
  System.out.println(set.first().name);
  // "Adam" is printed which is expected.
  </code></pre>
  
  <p><br/>
  <strong>3. Modifying the Person Instance P3 to have "zebra" name. i.e. Adam -> Zebra</strong></p>
  
  <pre><code>p3.name = "Zebra";
  
  System.out.println(set.first().name);
  </code></pre>
  
  <p><br/>
  <strong>QUESTION</strong> <br/>
  In Section 3, I modified <code>p3</code> instance to hold "Zebra" instead of "Adam". <br/><strong>Question is, How did TreeSet know that the P3 instance has been modified???</strong> <br/><br/>
  TreeSet is built using some Balanced BST (RB Trees usually). Hence, when I change some data, It has to reorder the internal nodes of the Tree to maintain adherence with the rules of the Comparator.
  <br/>
  <strong>So, how did the TreeSet get notified that the underlying data has been modified and that it has to reorder tree nodes again???</strong>
  <br/></p>
  
  <p>I really want to know how does it work internally. Is it observer pattern? <strong>Requesting a bit elaborate and comprehensive answers :)</strong></p>