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

 找回密码
 加入黑马

QQ登录

只需一步,快速开始

© linder_qzy 中级黑马   /  2015-3-12 11:08  /  906 人查看  /  3 人回复  /   0 人收藏 转载请遵从CC协议 禁止商业使用本文

Set里边的HashSet保证元素唯一性的原理是判断元素的HashCode值是否相同;
TreeSet保证元素唯一的依据是compareTo方法。相同返回0.
那么List集合里边有这种判断是否相同的机制呢?
我知道List集合里边元素是可以重复的。就是问问有没有这种比较的机制。

3 个回复

倒序浏览
TreeSet的compareTo()方法是排序的兄弟  唯一是equals
回复 使用道具 举报
wenke 发表于 2015-3-12 13:26
TreeSet的compareTo()方法是排序的兄弟  唯一是equals

这位兄弟你说的不对 TreeSet比较唯一用的就是compareTo(),TreeSet在存入元素的时候根本就不会调用equals方法。

我给你写个自己看下吧
  1. import java.util.*;
  2. class Student implements Comparable
  3. {
  4.         private int age;
  5.         private String name;
  6.         Student(String name,int age)
  7.         {
  8.                 this.age = age;
  9.                 this.name = name;
  10.         }
  11.         public int compareTo(Object obj)
  12.         {
  13.                 System.out.println("compareTo");
  14.                 if(!(obj instanceof Student))
  15.                         throw new RuntimeException("不是学生类!!");
  16.                 Student s = (Student)obj;
  17.                 if(this.age>s.age)
  18.                         return 1;
  19.                 if(this.age==s.age)
  20.                 {
  21.                         return this.name.compareTo(s.name);
  22.                 }
  23.                 return -1;
  24.         }
  25.         public boolean equals(Object obj){
  26.                 System.out.println("我是equals");
  27.                 return false;
  28.         }
  29.         public String getName()
  30.         {
  31.                 return name;
  32.         }
  33.         public int getAge()
  34.         {
  35.                 return age;
  36.         }
  37. }
  38. class DemoTreeSet
  39. {
  40.         public static void main(String[] args)
  41.         {
  42.                 TreeSet ts = new TreeSet();
  43.                 ts.add(new Student("张三",18));
  44.                 ts.add(new Student("李四",19));
  45.                 ts.add(new Student("王五",19));
  46.                 ts.add(new Student("赵六",20));
  47.                 ts.add(new Student("赵六",20));//重复记录
  48.                 Iterator it = ts.iterator();
  49.                 while(it.hasNext())
  50.                 {
  51.                         Student s = (Student)it.next();
  52.                         System.out.println(s.getName()+"........"+s.getAge());
  53.                 }
  54.         }
  55. }
  56. /*运行结果
  57. * compareTo
  58.    compareTo
  59.    compareTo
  60.    compareTo
  61. 张三........18
  62. 李四........19
  63. 王五........19
  64. 赵六........20
  65. * */
复制代码

如果用到equals方法是会打印“我是equals”这句话的
回复 使用道具 举报
List集合里的contains()方法  包括remove()方法 内部都是通过equanls()方法判断是否包含  或者是否删除成功的  这算是你要知道的比较机制吗
回复 使用道具 举报
您需要登录后才可以回帖 登录 | 加入黑马