java set唯一吗_java-TreeSet实现唯一性

简单其区别一下HashSet和TreeSet

唯一性原因

HashSet:

通过hashCode()方法,==和equals()方法来保证元素的是否相同

TreeSet:

通过comparaTo或者compare方法中的来保证元素的唯一性,元素是以二叉树的形式存放的。

TreeSet实现

public class Student implements Comparable {

//使用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) {

TreeSetst=new TreeSet();

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方法

939a8260b2450f4370889bce83e95679.png

d1358d4695d8660de2972cc1f6e682b2.png

Available time

发布了44 篇原创文章 · 获赞 71 · 访问量 5205

私信

关注

标签:唯一性,java,weight,int,age,height,Student,public,TreeSet

来源: https://blog.csdn.net/weixin_45822638/article/details/104089369

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值