Set 二(TreeSet与HashSet)十五

xiaoxiao2021-02-28  120

import java.util.HashSet; import java.util.Set; /**  *      set  *   /       \  * HashSet  TreeSet   * 1.HashSet 存储元素必须重写hashCode()与equals()方法,我们似乎没关心过;元素不重复  * HashSet底层实现是HashMap,HashMap的底层实现是:数组+链表,其存储元素分  *   2步:  *   1)判断hashCode()  如果相等  2)再判断equals()  *   靠1)2)保证去重,如果不重写上面2个方法,你试试就知道了。。。。。  * 2.TreeSet 存储元素可以排序,返回0去重  *   1)排序元素类必须实现java.util.lang.Comparable,重写comparaTo()方法。  *    提供空构造  new TreeSet()  *   2)提供另外的排序业务类,实现java.util.lang.Comparator,重写compare  *    new TreeSet(Comparator<? super E> comparator)  */ public class HashSetTest2 { public static void main(String[] args) { //元素本身实现java.util.lang.Comparable 的comparaTo Person1 p1=new Person1("张三","41042519800308353"); Person1 p2=new Person1("张三","41042519800308353"); Set<Person1> set1=new HashSet<Person1>(); set1.add(p1); set1.add(p2); System.out.println(set1); //结果:[Person:姓名:张三,年龄:41042519800308353,Person:姓名:张三,年龄:41042519800308353]  //。自然社会中,这个是一个人 System.out.println("=========================="); Set<Person11> set11=new HashSet<Person11>(); Person11 p11=new Person11("张三","41042519800308353"); Person11 p12=new Person11("张三","41042519800308353"); set11.add(p11); set11.add(p12); System.out.println(set11); //结果:[Person:姓名:张三,年龄:41042519800308353] } } //==========不重写hashCode()与equals()方法============================ class Person1  { private String name; private String id;//身份证 public Person1() { } public Person1(String name, String id) { super(); this.name = name; this.id = id; } @Override public String toString() { return "Person:姓名:"+this.name+",年龄:"+this.id; } } //============重写hashCode()与equals()方法==================== class Person11  { private String name; private String id;//身份证 public Person11() { } public Person11(String name, String id) { super(); this.name = name; this.id = id; } @Override public String toString() { return "Person:姓名:"+this.name+",年龄:"+this.id; } @Override public int hashCode() { return this.id.hashCode(); } @Override public boolean equals(Object obj) { if (obj instanceof Person11) { // Person11 p = (Person11) obj; return (name.equals(p.name) && id == p.id); } return super.equals(obj); } }
转载请注明原文地址: https://www.6miu.com/read-69026.html

最新回复(0)