日期:2014-05-20  浏览次数:20705 次

发一段CompareTo 方法的例子,其中很有意思的一段输出,大家看看,都代表了什么?
这段代码主要是进行 0 和 1 的大小比较。但是通过 println() 却看到输出了好几条结果,大家帮忙看看这些结果都分别代表了什么意思。
Java code
import java.util.*;

class SetType {
  int i;
  public SetType(int n) { i = n; }
  public boolean equals(Object o) {
    return o instanceof SetType && (i == ((SetType)o).i);
  }
  public String toString() { return Integer.toString(i); }
}

class TreeType extends SetType
implements Comparable<TreeType> {
  public TreeType(int n) { super(n); }
  public int compareTo(TreeType arg) {
    System.out.println("arg.i= " + arg.i + " i= " + i);  //关键看这里
    return (arg.i < i ? -1 : (arg.i == i ? 0 : 1));
  }
}

public class TypesForSets {
  static <T> Set<T> fill(Set<T> set, Class<T> type) {
    try {
      for(int i = 0; i < 2; i++)
          set.add(
            type.getConstructor(int.class).newInstance(i));
    } catch(Exception e) {
      throw new RuntimeException(e);
    }
    return set;
  }
  static <T> void test(Set<T> set, Class<T> type) {
    fill(set, type);
    fill(set, type); // Try to add duplicates
    fill(set, type);
    System.out.println(set);
  }
  public static void main(String[] args) {
    test(new TreeSet<TreeType>(), TreeType.class);

  }
}


输出:
arg.i= 0 i= 1 //怎么有这么多条啊?居然有7条,这每条都什么意思呢?
arg.i= 0 i= 0
arg.i= 0 i= 1
arg.i= 1 i= 1
arg.i= 0 i= 0
arg.i= 0 i= 1
arg.i= 1 i= 1
[1, 0] //这是最终结果(才2个结果,居然用了7条来比较,真是匪夷所思)


------解决方案--------------------
Java code

 return (arg.i < i ? -1 : (arg.i == i ? 0 : 1));

------解决方案--------------------
树状结构
第一次fill
插0不比较 树为 0

插1和0比较1次 树为 0
|
1

第二次fill 
插0时和已插入的0比较1次
插1时先和0比较,再和1比较, 比较2次

第三次fill同第二次

所以一共比较了7次

------解决方案--------------------
第一次调用fill:
尝试将“0”添加到TreeSet对象:由于TreeSet对象为空,直接将0作为TreeSet对象的根节点。
尝试将“1”添加到TreeSet对象:与TreeSet对象的根节点比较,输出 arg.i= 0 i= 1。
根节点没有子节点,于是将“1”添加为“0”的左子节点。
第二次调用fill:
尝试将“0”添加到TreeSet对象:与根节点“0”比较,输出 arg.i= 0 i= 0。
由于“0”已经是TreeSet中的元素,此时不会添加新的节点。
尝试将“1”添加到TreeSet对象:与根节点“0”比较,输出 arg.i= 0 i= 1。
与子节点“1”比较,输出 arg.i= 1 i= 1。
由于“1”已经是TreeSet中的元素,此时不会添加新的节点。
第三次调用fill与第二次调用fill执行的步骤完全一致。