java-TreeSet实现唯一性

简单其区别一下HashSet和TreeSet

唯一性原因

HashSet:
通过hashCode()方法,==和equals()方法来保证元素的是否相同
TreeSet:
通过comparaTo或者compare方法中的来保证元素的唯一性,元素是以二叉树的形式存放的。

TreeSet实现

public class Student implements Comparable<Student> {
//使用Comparable方法
 private int age;
 private int height;
 private int weight;
 public int getAge() {
  return age;
 }
 public void setAge(int age) {
  this.age = age;
 }
 public int getHeight() {
  return height;
 }
 public void setHeight(int height) {
  this.height = height;
 }
 public int getWeight() {
  return weight;
 }
 public void setWeight(int weight) {
  this.weight = weight;
 }
 public Student(int age, int height, int weight) {
  super();
  this.age = age;
  this.height = height;
  this.weight = weight;
 }
public int hashCode() {
 return this.height | this.weight<<8|this.age<<16;
}
public boolean equals(Object obj) {
 if (obj==null) return false;
 if(obj==this) return true;
 if(obj instanceof Student) {
  Student s0=(Student)obj;
  return this.hashCode()==obj.hashCode();
 }
 return false;
}
@Override
public int compareTo(Student o) {
 // TODO Auto-generated method stub
 if(o==null) {
  return 1;
 }
 return this.height-o.height;
 //如果这两个对象的相减为0则认为相同
}
 }

TreeSetDemo

public class TreeSetDemo {
 public static void main(String[] args) {
TreeSet<Student>st=new TreeSet<Student>();
st.add(new Student(1,2,3));
st.add(new Student(3,2,1));
st.add(new Student(3,1,2));
//迭代TreeSet
for(Student s:st) {
 System.out.println(s);
  }
 }
}

结果:本应该是三个。但是有一个是相同的,相减为0了所以认定相同

fanyongjunwork.Student@30201
fanyongjunwork.Student@10302

TreeSet:线程不安全,可以对Set集合中的元素进行排序。
他的排序是怎么进行的呢?
第一种排序实现(自然排序): (实质 : 序过程中比较两个对象“大小”时使用的就是 Comparable 接口的 compareTo 方法)
第一步: 元素自身具备比较性 (比如说年龄)
第二步: 实现Compareable接口,覆盖其CompareTo方法
重写 compareTo方法

/*// TODO Auto-generated method stub
         return 0;
        //主要条件
         int num  =this.age-s.age;
         //次要条件
         //如果年龄和姓名相同。才是同一个元素
         //如果年龄相同,就比较名字,否则(年龄不相同,)返回的是年龄
         int num2 = num == 0? this.name.compareTo(s.name) :num ;
         return num2;*/
         主要条件以名字长度排序
         nt num = (this.name).length()  - s.name.length();
       次要条件 (如果名字长度相同,在比较名字内容是否相同)
         int num2 =num ==0? this.name.compareTo(s.name) :num;
     次要条件(如果名字长度相同,内容也相同,开始比较年龄)
   int num3 = num2==0? this.age-s.age :num2;
        return num3;
         //
                      comparable接口提供的compareTo 方法 ,该方法的返回值类型为 int ,如果返回值的值大于0,则代表
                         当前对象比obj对象大,反之,则相反。则这就是两个对象比较的其实 是compareTo方法
发布了50 篇原创文章 · 获赞 75 · 访问量 6680

猜你喜欢

转载自blog.csdn.net/weixin_45822638/article/details/104089369