java set唯一吗

编程入门 行业动态 更新时间:2024-10-16 08:26:37

<a href=https://www.elefans.com/category/jswz/34/1770091.html style=java set唯一吗"/>

java set唯一吗

简单其区别一下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.namepareTo(s.name) :num ;

return num2;*/

主要条件以名字长度排序

nt num = (this.name).length() - s.name.length();

次要条件 (如果名字长度相同,在比较名字内容是否相同)

int num2 =num ==0? this.namepareTo(s.name) :num;

次要条件(如果名字长度相同,内容也相同,开始比较年龄)

int num3 = num2==0? this.age-s.age :num2;

return num3;

//

comparable接口提供的compareTo 方法 ,该方法的返回值类型为 int ,如果返回值的值大于0,则代表

当前对象比obj对象大,反之,则相反。则这就是两个对象比较的其实 是compareTo方法

Available time

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

私信

关注

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

来源:

更多推荐

java set唯一吗

本文发布于:2024-03-23 16:23:43,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1740275.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:java   set   唯一吗

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!