日韩性视频-久久久蜜桃-www中文字幕-在线中文字幕av-亚洲欧美一区二区三区四区-撸久久-香蕉视频一区-久久无码精品丰满人妻-国产高潮av-激情福利社-日韩av网址大全-国产精品久久999-日本五十路在线-性欧美在线-久久99精品波多结衣一区-男女午夜免费视频-黑人极品ⅴideos精品欧美棵-人人妻人人澡人人爽精品欧美一区-日韩一区在线看-欧美a级在线免费观看

歡迎訪問 生活随笔!

生活随笔

當前位置: 首頁 > 编程资源 > 编程问答 >内容正文

编程问答

单列集合Set的实现类HashSet

發布時間:2023/12/3 编程问答 28 豆豆
生活随笔 收集整理的這篇文章主要介紹了 单列集合Set的实现类HashSet 小編覺得挺不錯的,現在分享給大家,幫大家做個參考.

Set接口 [Collection】的子類

HashSet

特點【無序,不可重復,不能排序】
默認比較地址值【地址相同的值相同】,重寫后可比較內容【內容相同的值相同】

1.比較地址值【默認】

public class Demo1 {public static void main(String[] args) {HashSet<Student> hs = new HashSet<>();Student s1 = new Student("張三", 18);Student s2 = new Student("李四", 18);Student s3 = new Student("張三", 18);System.out.println("s1:"+ s1.hashCode());System.out.println("s2:"+ s2.hashCode());System.out.println("s3:"+ s3.hashCode());System.out.println("s1:"+ s1.hashCode());hs.add(s1);hs.add(s2);hs.add(s3);for(Student student : hs){System.out.println(student);}} }打印結果: -------------------------------------------------------------- s1:189568618 s2:960604060 s3:1349393271 s1:189568618 Student{name='張三', age=18} Student{name='張三', age=18} Student{name='李四', age=18}

2.而默認比較地址值不能達到我們實際的要求,則需要重寫HashaCode方法使其比較屬性值

【API中有一些類已經重寫了HashaCode,給出了比較規則,如:String:數值大小、字符串長度 ]

public class Demo1 {public static void main(String[] args) {HashSet<String> hs = new HashSet<>();hs.add("hello");hs.add("world");hs.add("java");hs.add("java");hs.add("java");for (String h : hs) {System.out.println(h);}} } 打印結果: -------------------------------------------------------------- world java hello

【未重寫的類,如:我們自定義的類,則需要去類中重寫HashC ode方法】

public class Demo1 {public static void main(String[] args) {HashSet<Student1> hs = new HashSet<>();Student1 s1 = new Student1("張三", 18);Student1 s2 = new Student1("李四", 18);Student1 s3 = new Student1("張三", 18);hs.add(s1);hs.add(s2);hs.add(s3);for(Student1 student : hs){System.out.println(student);}} }class Student {private String name;private int age;public Student(String name, int age) {this.name = name;this.age = age;}@Overridepublic String toString() {return "Student{" +"name='" + name + '\'' +", age=" + age +'}';}@Overridepublic boolean equals(Object o) {if (this == o) return true;if (o == null || getClass() != o.getClass()) return false;Student student = (Student) o;if (age != student.age) return false;return Objects.equals(name, student.name);}@Overridepublic int hashCode() {int result = name != null ? name.hashCode() : 0;result = 31 * result + age;return result;} } 打印結果: ------------------------------------------------------------ Student{name='張三', age=18} Student{name='李四', age=18}

3.底層原理【鏈表,數組,[鏈表滿8為]紅黑樹】

計算哈希值 : 根據元素的哈希數和數組的長度取余得到存入的位置 如:21501220%16

注:兩種Set實現類的選擇:【如果你需要得到一個有序的結果時就應該使用TreeMap(因為HashMap中元素的排列順序是不固定的)。除此之外,由于HashMap有更好的性能,所以大多不需要排序的時候我們會使用HashMap】

總結

以上是生活随笔為你收集整理的单列集合Set的实现类HashSet的全部內容,希望文章能夠幫你解決所遇到的問題。

如果覺得生活随笔網站內容還不錯,歡迎將生活随笔推薦給好友。