A股上市公司传智教育(股票代码 003032)旗下技术交流社区北京昌平校区

 找回密码
 加入黑马

QQ登录

只需一步,快速开始

© 曾浩 中级黑马   /  2012-10-12 19:45  /  1502 人查看  /  4 人回复  /   0 人收藏 转载请遵从CC协议 禁止商业使用本文

public class TestTreeSet01 {

public static void main(String[] args) {

   TreeSet ts = new TreeSet(new NameCompare());

     ts.add(new Person01("zhang01",20));
  ts.add(new Person01("zhang02",17));
  ts.add(new Person01("zhang05",18));
  ts.add(new Person01("zhang03",18));
  ts.add(new Person01("zhang04",18));
  ts.add(new Person01("zhang05",18));
  ts.add(new Person("zhang03",18));
  Iterator i = ts.iterator();
  while(i.hasNext()){
   Person01 person = (Person01)i.next();
     System.out.println(person.getName()+"..."+person.getAge());
  }
              }
}
class Person01 implements Comparable {
private String name;
private int age;
Person01(String name,int age){
  this.name = name;
  this.age = age;
}
public String getPerson01(){
  return this.name+"..."+this.age ;
}
public String getName(){
  return this.name ;
}
public int getAge(){
  return this.age ;
}
public int compareTo(Object obj) {
  if(!(obj instanceof Person01)){
   throw new RuntimeException();
  }
  Person01 p = (Person01)obj;
  if(this.age>p.age){
   return 1;
  }else if(this.age==p.age){
   
   return this.name.compareTo(p.name);
  }
  return -1;
}

}
class NameCompare implements Comparator{

public int compare(Object o1, Object o2) {
  Person01 s1 = (Person01)o1;
  Person01 s2 = (Person01)o2;
   
   return s1.compareTo(s2); }
}
我是直接比较俩个对象 这是比较他们的hash值还是比较他们的属性值?
为什么我实现了Comparator接口 并且将他的对象传入到了TreeSet集合中 而输出的结果是用Comparable所定义自然排序输出的?

4 个回复

倒序浏览
return s1.compareTo(s2);

你这句就是调用你自己重写的方法啊,所以你用Comparator对象和不用是一个效果
回复 使用道具 举报
你定义外部比较器时,如果直接比较对象,最后调用的还是原来的自然排序方法,所以应该比较hashcode或者属性值。你这里就是因为在的比较器中调用的Comparable所定义的自然排序方法。
回复 使用道具 举报
    产生这类疑问的原因在于大家都喜欢只看API,但是不看JDK源码~~

   TreeSet的add方法实际上调用的是 TreeMap的put方法~~

    /**     * Associates the specified value with the specified key in this map.
     * If the map previously contained a mapping for the key, the old
     * value is replaced.
     *
     * @param key key with which the specified value is to be associated
     * @param value value to be associated with the specified key
     *
     * @return the previous value associated with <tt>key</tt>, or
     *         <tt>null</tt> if there was no mapping for <tt>key</tt>.
     *         (A <tt>null</tt> return can also indicate that the map
     *         previously associated <tt>null</tt> with <tt>key</tt>.)
     * @throws ClassCastException if the specified key cannot be compared
     *         with the keys currently in the map
     * @throws NullPointerException if the specified key is null
     *         and this map uses natural ordering, or its comparator
     *         does not permit null keys
     */
    public V put(K key, V value) {
        Entry<K,V> t = root;
        if (t == null) {
            // TBD:
            // 5045147: (coll) Adding null to an empty TreeSet should
            // throw NullPointerException
            //
            // compare(key, key); // type check
            root = new Entry<K,V>(key, value, null);
            size = 1;
            modCount++;
            return null;
        }
        int cmp;
        Entry<K,V> parent;
        // split comparator and comparable paths
        Comparator<? super K> cpr = comparator;//这个comparator是你传进来的比较器
       if (cpr != null) {如果不为空
            do {
                parent = t;
                cmp = cpr.compare(key, t.key);
                if (cmp < 0)
                    t = t.left;
                else if (cmp > 0)
                    t = t.right;
                else
                    return t.setValue(value);
            } while (t != null);
        }
        else {//如果没有传比较器
            if (key == null)
                throw new NullPointerException();
            Comparable<? super K> k = (Comparable<? super K>) key;
            do {
                parent = t;
                cmp = k.compareTo(t.key);
                if (cmp < 0)
                    t = t.left;
                else if (cmp > 0)
                    t = t.right;
                else
                    return t.setValue(value);
            } while (t != null);
        }
        Entry<K,V> e = new Entry<K,V>(key, value, parent);
        if (cmp < 0)
            parent.left = e;
        else
            parent.right = e;
        fixAfterInsertion(e);
        size++;
        modCount++;
        return null;
    }
   
回复 使用道具 举报
TreeSet treeSet =new TreeSet(new Comparator(){
                         public int compare(Object o1, Object o2){
                                 Student s1=(Student)o1;
                                 Student s2=(Student)o2;
                                 //按成绩降序
                                return s2.getScore()-s1.getScore();
                         }
                });

我以前做的 看红色部分
回复 使用道具 举报
您需要登录后才可以回帖 登录 | 加入黑马