Javaクイズ(Sorted編)

指定したComparatorに従って、addされた要素をソートした状態で保持してくれるSortedSet*1

以下のコードは、どのような結果になるでしょうか? 分からなかったので試してみた。

public class SortedSample {
  
  public static void main(String[] args) {
    Set<Model> treeSet = new TreeSet<Model>(new Comparator<Model>() {
      public int compare(Model o1, Model o2) {
        return o1.string.compareTo(o2.string);
      }
    });
    
    Model a = new Model("a");
    Model b = new Model("b");
    treeSet.add(a);
    treeSet.add(b);
    
    a.string = "z";
    
    for(Model m : treeSet) {
      System.out.print(m.string);
    }
  }
  
  static class Model {
    String string;
    
    Model(String string) {
      this.string = string;
    }
  }
}
  1. bz
  2. zb

なるほどね(一人で納得してみる)。

*1:SortedMapってのもある