title: Sorting objects in a recursive generic data structure
body: <p>I have a generic tree class in which each tree node holds some data. Each piece of data has one attribute of the type String. I want to sort each tree node's children alphabetically by this attribute.</p>
  
  <p>The Tree class:</p>
  
  <pre><code>public class Tree&lt;T&gt;{
      public T data;
      public List&lt;Tree&lt;T&gt;&gt; children = new ArrayList&lt;Tree&lt;T&gt;&gt;();
  }
  </code></pre>
  
  <p>Note that the tree's children are of type Tree!</p>
  
  <p>An example actual type parameter for the Tree class is the following:</p>
  
  <pre><code>public class DataItem{
      public String name;
  }
  </code></pre>
  
  <p>My idea is to extend the Tree class with a sort() method and use a Comparator like the following but I am stuck at the comparison function:</p>
  
  <pre><code>public class Tree&lt;T&gt;{
      public T data;
      public List&lt;Tree&lt;T&gt;&gt; children = new ArrayList&lt;Tree&lt;T&gt;&gt;();
  
      public void sort(){
          Collections.sort(this.children,
              new Comparator&lt;Tree&lt;T&gt;&gt;(){
                  @Override
                  public int compare(Tree&lt;T&gt; objectA, Tree&lt;T&gt; objectB){
                      //I am stuck here!
                      return 0;
                  }
              }
          );
          for(Tree&lt;T&gt; child: this.children){
              child.sort();
          }
      }
  }
  </code></pre>
  
  <p>I have different ideas to solve this problem:</p>
  
  <ul>
  <li>Use reflection to acces the objects' attributes and compare them.</li>
  <li>Implement the interface Comparable in DataItem. </li>
  <li><p>Use a new interface to acces the objects' attribute for comparison:</p>
  
  <pre><code>public interface GetComparisonAttribute {
      public String getComparisonAttribute();
  }
  
  public class DataItem implements GetComparisonAttribute{
      public String name;
  
      @Override
      public String GetComparisonAttribute(){
          return this.name;
      }
  }
  
  //the comparison function inside Tree&lt;T&gt;.sort():
  public int compare(Tree&lt;T&gt; objectA, Tree&lt;T&gt; objectB){
      return objectA.data.getComparisonAttribute()
          .compareToIgnoreCase(objectB.data.getComparisonAttribute());
  }
  </code></pre></li>
  </ul>
  
  <p>What is the right or best thing to do? Are there any other ways?</p>
  
  <p>It may be important to be able to specify the sorting attribute.</p>
  
  <p>I think it would be nice to use Collections.sort() directly on a Tree but implementing it in this recursive data structure really confuses me. A downside of doing it this way is that I cannot specify the sorting attribute.</p>