麻豆小视频在线观看_中文黄色一级片_久久久成人精品_成片免费观看视频大全_午夜精品久久久久久久99热浪潮_成人一区二区三区四区

首頁 > 學院 > 開發設計 > 正文

黑馬程序員_JavaSE學習總結第17天_集合框架3

2019-11-15 00:18:53
字體:
來源:轉載
供稿:網友
黑馬程序員_javaSE學習總結第17天_集合框架3

------- android培訓、java培訓、期待與您交流! ----------

17.01 ArrayList集合的toString()方法源碼解析

代碼:

Collection c = new ArrayList();

c.add("hello");

c.add("world");

c.add("java");

System.out.PRintln(c);

輸出c時默認調用的是c的toString()方法

A:Collection c = new ArrayList();

這是多態,所以輸出c的 toString()方法,其實是輸出ArrayList的toString()方法

B:看 ArrayList 的 toString()方法

在ArrayList里面卻沒有發現toString()。應該去父類查找→ AbstractList → AbstractCollection

C:toString()的方法源碼

 1 public String toString()  2 { 3     Iterator<E> it = iterator(); //集合本身調用迭代器方法,得到集合迭代器 4     if (! it.hasNext()) 5         return "[]"; 6  7     StringBuilder sb = new StringBuilder(); 8     sb.append('['); 9     for (;;) 10     {11         E e = it.next(); //e=hello,world,java12         sb.append(e == this ? "(this Collection)" : e);13         if (! it.hasNext())14             //[hello, world, java]15             return sb.append(']').toString();16         sb.append(',').append(' ');17     }18 }

17.02 Set集合概述及特點

Set接口概述:一個不包含重復元素的 collection

特點:

無序(存入與取出的順序不一致)

唯一(存入集合的元素唯一)

17.03 HashSet存儲字符串并遍歷

HashSet類概述:不保證 set 的迭代順序,特別是它不保證該順序恒久不變。此類允許使用 null 元素。

例:

 1 public class Practice  2 { 3     public static void main(String[] args) 4     { 5         HashSet<String> hs = new HashSet<String>(); 6         hs.add("hello"); 7         hs.add("world"); 8         hs.add("world"); 9         hs.add("java");10         11         for (String s : hs) 12         {13             System.out.println(s);14         }15     }16 }

運行結果:

hellojavaworld

17.04 HashSet保證元素唯一性的源碼解析

 1 interface Collection 2 {...} 3  4 interface Set extends Collection  5 {...} 6  7 class HashSet implements Set  8 { 9     private static final Object PRESENT = new Object();10     private transient HashMap<E,Object> map;11     12     public HashSet() 13     {14         map = new HashMap<>();15     }16     17     public boolean add(E e) 18     { //e=hello,world19         return map.put(e, PRESENT)==null;20     }21 }22 23 class HashMap implements Map 24 {25     public V put(K key, V value) 26     { //key=e=hello,world27     28         //看哈希表是否為空,如果空,就開辟空間29         if (table == EMPTY_TABLE) 30         {31             inflateTable(threshold);32         }33         34         //判斷對象是否為null35         if (key == null)36             return putForNullKey(value);37         38         int hash = hash(key); //和對象的hashCode()方法相關39         40         //在哈希表中查找hash值41         int i = indexFor(hash, table.length);42         for (Entry<K,V> e = table[i]; e != null; e = e.next) 43         {44             //這次的e其實是第一次的world45             Object k;46             if (e.hash == hash && ((k = e.key) == key || key.equals(k))) 47             {48                 V oldValue = e.value;49                 e.value = value;50                 e.recordaccess(this);51                 return oldValue;52                 //走這里其實是沒有添加元素53             }54         }55 56         modCount++;57         addEntry(hash, key, value, i); //把元素添加58         return null;59     }60     61     transient int hashSeed = 0;62     63     final int hash(Object k) 64     { //k=key=e=hello,65         int h = hashSeed;66         if (0 != h && k instanceof String) 67         {68             return sun.misc.Hashing.stringHash32((String) k);69         }70 71         h ^= k.hashCode(); //這里調用的是對象的hashCode()方法72 73         // This function ensures that hashCodes that differ only by74         // constant multiples at each bit position have a bounded75         // number of collisions (approximately 8 at default load factor).76         h ^= (h >>> 20) ^ (h >>> 12);77         return h ^ (h >>> 7) ^ (h >>> 4);78     }79 }

通過查看add方法的源碼,知道這個方法底層依賴兩個方法:hashCode()和equals()。

判斷元素唯一性的方式:通過對象的hashCode和equals方法來完成元素唯一性

如果對象的hashCode值不同,那么不用判斷equals方法,就直接存儲到哈希表中。

如果對象的hashCode值相同,那么要再次判斷對象的equals方法是否為true。

如果為true,視為相同元素,不存。如果為false,那么視為不同元素,就進行存儲。

如果類沒有重寫這兩個方法,默認使用的Object()。一般來說不會相同。

17.05 HashSet存儲自定義對象并遍歷

 1 public class Practice  2 { 3     public static void main(String[] args) 4     { 5         HashSet<Student> hs = new HashSet<Student>(); 6          7         hs.add(new Student("小明",23)); 8         hs.add(new Student("旺財",12)); 9         hs.add(new Student("旺財",12));10         hs.add(new Student("小強",24));11         hs.add(new Student("小明",22));12         hs.add(new Student("小紅",22));13         14         for(Student s : hs)15         {16             System.out.println(s.getName()+":"+s.getAge());17         }18     }19 }

17.06 HashSet保證元素唯一性的代碼體現

上例中重復元素被存入到了集合中,因為Student沒有重寫hashCode和equals方法,默認使用的Object()的hashCode和equals方法,一般來說結果不會相同,所以存入到了集合中,Student類應重寫hashCode和equals方法(自動生成)。

 1    @Override 2     public int hashCode()  3     { 4         final int prime = 31; 5         int result = 1; 6         result = prime * result + age; 7         result = prime * result + ((name == null) ? 0 : name.hashCode()); 8         return result; 9     }10 11     @Override12     public boolean equals(Object obj) 13     {14         if (this == obj)15             return true;16         if (obj == null)17             return false;18         if (getClass() != obj.getClass())19             return false;20         Student other = (Student) obj;21         if (age != other.age)22             return false;23         if (name == null) 24         {25             if (other.name != null)26                 return false;27         } else if (!name.equals(other.name))28             return false;29         return true;30     }

17.07 LinkedHashSet的概述和使用

LinkedHashSet類概述:

元素有序唯一:由鏈表保證元素有序、由哈希表保證元素唯一

例:

 1 public class Practice  2 { 3     public static void main(String[] args) 4     { 5         LinkedHashSet<String> hs = new LinkedHashSet<String>(); 6         hs.add("hello"); 7         hs.add("world"); 8         hs.add("world"); 9         hs.add("java");10         11         for(String s : hs)12         {13             System.out.println(s);14         }15     }16 }

運行結果:

helloworldjava

17.08 TreeSet存儲Integer類型的元素并遍歷

TreeSet類概述:使用元素的自然順序對元素進行排序,或者根據創建 set 時提供的 Comparator 進行排序,具體取決于使用的構造方法。

例:

 1 public class Practice  2 { 3     public static void main(String[] args) 4     { 5         TreeSet<Integer> ts = new TreeSet<Integer>(); 6         ts.add(20); 7         ts.add(18); 8         ts.add(23); 9         ts.add(22);10         ts.add(17);11         ts.add(24);12         ts.add(19);13         ts.add(18);14         15         for(Integer i : ts)16         {17             System.out.print(i+" ");18         }19     }20 }

運行結果:

17 18 19 20 22 23 24 

17.09 TreeSet保證元素排序的源碼解析

 1 interface Collection {...} 2  3 interface Set extends Collection {...} 4  5 interface NavigableMap {} 6  7 class TreeMap implements NavigableMap  8 { 9      public V put(K key, V value) 10     {11         Entry<K,V> t = root;12         if (t == null) 13         {14             compare(key, key); // type (and possibly null) check15 16             root = new Entry<>(key, value, null);17             size = 1;18             modCount++;19             return null;20         }21         int cmp;22         Entry<K,V> parent;23         // split comparator and comparable paths24         Comparator<? super K> cpr = comparator;25         if (cpr != null) 26         {27             do 28             {29                 parent = t;30                 cmp = cpr.compare(key, t.key);31                 if (cmp < 0)32                     t = t.left;33                 else if (cmp > 0)34                     t = t.right;35                 else36                     return t.setValue(value);37             } while (t != null);38         }39         else 40         {41             if (key == null)42                 throw new NullPointerException();43             Comparable<? super K> k = (Comparable<? super K>) key;44          do 45             {46                 parent = t;47                 cmp = k.compareTo(t.key);48                 if (cmp < 0)49                     t = t.left;50                 else if (cmp > 0)51                     t = t.right;52                 else53                     return t.setValue(value);54             } while (t != null);55         }56         Entry<K,V> e = new Entry<>(key, value, parent);57         if (cmp < 0)58             parent.left = e;59         else60             parent.right = e;61         fixAfterInsertion(e);62         size++;63         modCount++;64         return null;65     }66 }67 68 class TreeSet implements Set 69 {70     private transient NavigableMap<E,Object> m;71     72     public TreeSet() 73     {74          this(new TreeMap<E,Object>());75     }76 77     public boolean add(E e) 78     {79         return m.put(e, PRESENT)==null;80     }81 }

真正的比較是依賴于元素的compareTo()方法,而這個方法是定義在 Comparable里面的。

所以,要想重寫該方法,就必須是先實現 Comparable接口。這個接口表示的就是自然排序。

17.10 TreeSet保證元素唯一性和自然排序的原理和圖解

17.11 TreeSet存儲自定義對象并遍歷練習1

Student類實現自然排序接口Comparable,重寫compareTo()方法

1 @Override2 public int compareTo(Student s) 3 {4     //主要條件,按年齡排5     int num = this.age - s.age;6     //次要條件,年齡相同按姓名排7     int num2 = (num == 0)?this.name.compareTo(s.name):num;8     return num2;9 }

17.12 TreeSet存儲自定義對象并遍歷練習2

Student類實現自然排序接口Comparable,重寫compareTo()方法

 1 @Override 2 public int compareTo(Student s)  3 { 4     // 主要條件 姓名的長度 5     int num = this.name.length() - s.name.length(); 6     // 姓名的長度相同,比較姓名的內容是否相同 7     int num2 = num == 0 ? this.name.compareTo(s.name) : num; 8     // 姓名的長度和內容相同,比較年齡是否相同,繼續判斷年齡 9     int num3 = num2 == 0 ? this.age - s.age : num2;10     return num3;11 }

17.13 TreeSet保證元素唯一性和比較器排序的原理及代碼實現

 1 // 比較器排序,讓集合具備比較性,匿名內部類實現 2 TreeSet<Student> ts = new TreeSet<Student>(new Comparator<Student>()  3 { 4     @Override 5     public int compare(Student s1, Student s2)  6     { 7         // 姓名長度 8         int num = s1.getName().length() - s2.getName().length(); 9         // 姓名內容10         int num2 = num == 0 ? s1.getName().compareTo(s2.getName()) : num;11         // 年齡12         int num3 = num2 == 0 ? s1.getAge() - s2.getAge() : num2;13         return num3;14     }15     16 });

17.14 TreeSet對元素排序的總結

唯一性:根據比較的返回的是否是0來決定

排序: 1.自然排序,一個類的元素想要進行自然排序就必須實現自然排序接口Comparable(元素具備比較性)

   2.比較器排序,讓集合的構造方法接收一個比較器接口的子類對象Comparator(集合具備比較性)

17.15 產生10個1-20之間的隨機數要求隨機數不能重復案例簡潔版

編寫一個程序,獲取10個1至20的隨機數,要求隨機數不能重復。

 1 public class Practice  2 { 3     public static void main(String[] args) 4     { 5         // 創建隨機數對象 6         Random r = new Random(); 7  8         // 創建一個Set集合 9         HashSet<Integer> ts = new HashSet<Integer>();10 11         // 判斷集合的長度是不是小于1012         while (ts.size() < 10) 13         {14             int num = r.nextInt(20) + 1;15             ts.add(num);16         }17 18         // 遍歷Set集合19         for (Integer i : ts) 20         {21             System.out.println(i);22         }23     }24 }

17.16 鍵盤錄入學生信息按照總分排序后輸出在控制臺案例

Student類

 1 public class Student 2 { 3     private String name; 4     private int chinese; 5     private int math; 6     private int english; 7     public Student(String name, int chinese, int math, int english)  8     { 9         super();10         this.name = name;11         this.chinese = chinese;12         this.math = math;13         this.english = english;14     }15     public String getName() 16     {17         return name;18     }19     public void setName(String name) 20     {21         this.name = name;22     }23     public int getChinese() 24     {25         return chinese;26     }27     public void setChinese(int chinese) 28     {29         this.chinese = chinese;30     }31     public int getMath() 32     {33         return math;34     }35     public void setMath(int math) 36     {37         this.math = math;38     }39     public int getEnglish() 40     {41         return english;42     }43     public void setEnglish(int english) 44     {45         this.english = english;46     }47     48     public int getSum()49     {50         return this.chinese+this.english+this.math;51     }52 }

測試類

 1 public class Practice  2 { 3     public static void main(String[] args) 4     { 5         TreeSet<Student> ts = new TreeSet<Student>(new Comparator<Student>()  6         { 7             @Override 8             public int compare(Student s1, Student s2)  9             {10                 //按總分比較11                 int num1 = s2.getSum() - s1.getSum();12                 //總分相同按語文成績比較13                 int num2 = num1==0?s1.getChinese() - s2.getChinese():num1;14                 //語文成績相同按數學成績比較15                 int num3 = num2==0?s1.getMath() - s2.getMath():num2;16                 //數學成績相同按英語成績比較17                 int num4 = num3==0?s1.getChinese() - s2.getChinese():num3;18                 //英語成績相同按姓名比較19                 int num5 = num4==0?s1.getName().compareTo(s2.getName()):num4;20                 return num5;21             }22         });23         for (int i = 1; i <= 5; i++) 24         {25             Scanner sc = new Scanner(System.in);26             System.out.println("請輸入第"+i+"位學生的姓名");27             String name = sc.nextLine();28             System.out.println("請輸入第"+i+"位學生的語文成績");29             String chinese = sc.nextLine();30             System.out.println("請輸入第"+i+"位學生的數學成績");31             String math = sc.nextLine();32             System.out.println("請輸入第"+i+"位學生的英語成績");33             String english = sc.nextLine();34             35             Student s = new Student(name, Integer.parseInt(chinese), Integer.parseInt(math), Integer.parseInt(english));36             ts.add(s);37         }38         System.out.println("學生信息如下");39         System.out.println("姓名/t語文/t數學/t英語/t總分");40         for(Student s:ts)41         {42             System.out.println(s.getName()+"/t"+s.getChinese()+"/t"+s.getMath()+"/t"+s.getEnglish()+"/t"+s.getSum());43         }44     }45 }

運行結果:


發表評論 共有條評論
用戶名: 密碼:
驗證碼: 匿名發表
主站蜘蛛池模板: 精品成人国产在线观看男人呻吟 | 日日草夜夜草 | 欧美日韩亚洲国产 | 色交视频 | 国产精品视频海角社区88 | 日本xxxx色视频在线观看免费, | wwwxxx免费视频 | 国产成人在线免费视频 | 依人九九宗合九九九 | 龙的两根好大拔不出去h | 色97在线 | 久久精品操 | 2018亚洲男人天堂 | 欧美视频一二三区 | 日本黄色免费播放 | 成人午夜视频在线观看 | 97黄色网 | 91久久久久 | 香蕉成人在线观看 | 一级黄色电影网站 | 一级做受毛片免费大片 | av免费在线播放网址 | 欧美一级在线看 | 欧美在线中文字幕 | 成人午夜在线免费观看 | 中国a毛片 | 九九热精品在线 | 国产精品观看在线亚洲人成网 | 视频国产一区二区 | 91短视频版高清在线观看免费 | 国产精品久久久久久久久久久久久久久久 | 久久精品视频首页 | 国产一有一级毛片视频 | 成人不卡免费视频 | 高潮娇喘嗯啊~文字 | 国产91在线高潮白浆在线观看 | 成人区一区二区 | 国产精品视频一区二区三区四区国 | 欧日韩在线视频 | 麻豆视频在线播放 | 欧美视频国产 |