public class UserModel implements Comparable {
private String userId,name;
private int age;

public String getUserId() {
return userId;
}
public void setUserId(String useId) {
this.userId = useId;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}

@Override
public String toString(){
return "userId="+userId+",name="+name+",age="+age;
}

@Override
public int hashCode() {
System.out.println("call hashCode----------------------------->");
final int PRIME = 31;
int result = 1;
result = PRIME * result + ((userId == null) ? 0 : userId.hashCode());
return result;
}

@Override
public boolean equals(Object obj) {
System.out.println("call equals----------------------------->");
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
final UserModel other = (UserModel) obj;
if (userId == null) {
if (other.userId != null)
return false;
} else if (!userId.equals(other.userId))
return false;
return true;
} public int compareTo(Object o) {
// TODO Auto-generated method stub
System.out.println("call compareTo----------------------------->");
UserModel user=(UserModel)o;
if(this.getUserId().compareTo(user.getUserId())>0){
return 1;
}else if(this.getUserId().compareTo(user.getUserId())==0){
    return 0;
}return -1;
}}
////////////////////////////////////////////////////////////////////////////////////////////
public class MyComparator implements java.util.Comparator<UserModel> { public int compare(String o1, String o2) {
// TODO Auto-generated method stub
int a = Integer.parseInt(o1);
int b = Integer.parseInt(o2);
return (a>b?1:(a==b?0:-1));
}

public int compare(int a, int b) {
// TODO Auto-generated method stub

return (a>b?1:(a==b?0:-1));
}

public int compare(UserModel o1,UserModel o2) {
String id1 = o1.getUserId();
String id2 = o2.getUserId();
int age1 = o1.getAge();
int age2 = o2.getAge();
return (compare(id1, id2) == 0 ? compare(age1, age2) : compare(id1, id2)); 
}
}
////////////////////////////////////////////////////////////////////////////////////////////
import java.util.*;import com.test6.视频教程.MyComparator;public class TreeSetTest {
private void testTreeSet(){
Set set = new TreeSet(new MyComparator());//用了我的比较器,就可以加入重复的元素,什么原因呀?
       //Set set = new TreeSet();//这个是默认的TreeSet实例,就不可以加,什么原因呀~ UserModel um1=new UserModel();
um1.setUserId("3");
um1.setName("张三");
um1.setAge(20);

UserModel um2=new UserModel();
um2.setUserId("4");
um2.setName("赵柳");//李四
um2.setAge(21);

UserModel um3=new UserModel();
um3.setUserId("2");
um3.setName("王五");
um3.setAge(23);

UserModel um4=new UserModel();
um4.setUserId("3");
um4.setName("赵柳");
um4.setAge(29);

set.add(um1);
set.add(um2);
set.add(um3);
set.add(um4);

Iterator it = set.iterator();
while(it.hasNext()){
UserModel a = (UserModel)it.next();
System.out.println("a=="+a);
}
}
public static void main(String[] args)throws Exception {
TreeSetTest col = new TreeSetTest();
col.testTreeSet();
}
}

解决方案 »

  1.   

    你的UserModel里的equals只要两个元素的userId相同就算同一个元素,而MyComparator里要userId和age都相同才算是同一个元素,比较的原则不同,结果当然不同了。
      

  2.   

     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;
            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.put(key,value)方法不难发现,实际上TreeSet在put值的时候,使用了排序二叉树的查找算法(因为TreeSet的内部数据结构就是一个平衡二叉树),其中会调用自定义Comparator的compare方法,如果返回为0的话那么Set会用当前value代替原先的的value,lz的Mycomparator中id想等的情况下会比较age,自然给出的测试数据是不重复的,而如果不用MyComparator则TreeSet会调用UserModel自身的compare方法,单独比较id,则会出现重复的值。
      

  3.   

    那1楼的师傅,怎么才能在MyComparator里判断,才能使的在TreeSetTest 中不能加入重复的元素呢?
      

  4.   

    TreeSet中放入的Java Object 会自动调用equals、compareTo方法
    如果对象不是Java API本身的,程序员需要重写这个方法
    最后说一下,TreeSet中比较相等的对象将会覆盖以前的那个
    ========================================================
    也就是说TreeSet本身不支持放入多个重复元素
      

  5.   

    TreeSet 这是一个不可以放重复的东西的, 这个就有点类似高中数学里面的集合,TreeSet如果里面存放的是数字, 就相当于 Colletions.sort(list);可以排序的,是升序。
      

  6.   

    高手们  TreeSet里面不可以放相同的元素是吗?求高手帮忙
      

  7.   

    今天我写了一个TreeSet东西
    ts.add(new Student(1,"zhangsan"));
    ts.add(new Student(2,"wangwu"));
    ts.add(new Student(3,"huangmx"));
    ts.add(new Student(2,"lisi"));
    比如这样的最后结果只有三个,那个2相同的打印不出来,这样的情况说明重复吗?
    请高手帮忙