Javase Learning Summary 17th Day _ Collection Frame 3

Source: Internet
Author: User
Tags comparable set set

17.01 ArrayList Collection of ToString () method source code parsing

Code:

Collection C = new ArrayList ();

C.add ("Hello");

C.add ("World");

C.add ("Java");

System.out.println (c);

The ToString () method of C is called by default when output C

A:collection C = new ArrayList ();

This is polymorphic, so the ToString () method of output C is actually the ToString () method of the output ArrayList

B: Look at the toString () method of ArrayList

No ToString () was found in ArrayList. Should go to the parent class to find →abstractlist→abstractcollection

C:tostring () method source code

1 public String toString ()  2 {3     iterator<e> it = Iterator ();//The collection itself calls the iterator method to get the set iterator 4     if (! It.hasnext () ) 5         return "[]"; 6  7     StringBuilder sb = new StringBuilder (); 8     sb.append (' ['); 9 for     (;;)     {11< C10/>e E = It.next (); E=hello,world,java12         sb.append (E = = this?) "(This Collection)": E), and         if (! It.hasnext ())             //[hello, World, java]15             return sb.append ('] '). ToString ();         sb.append (', '). Append (");     }18}

Overview and features of the 17.02 set set

Set interface Overview: A collection that does not contain duplicate elements

Characteristics:

Unordered (inconsistent in order of deposit and withdrawal)

Unique (the element that is stored in the collection is unique)

17.03 HashSet store strings and traverse

HashSet class Overview: The set iteration order is not guaranteed, especially if it does not guarantee that the order is constant. This class allows the use of NULL elements.

Cases:

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");         String s:hs)         {             System.out.println (s);         }15     }16}

Operation Result:

Hellojavaworld

17.04 HashSet guarantee Element uniqueness of source code parsing

 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 (); transient hashmap<e,object> map;11-PU Blic HashSet () () {map = new hashmap<> ();}16. Public boolean Add (E e) {//e=h ELLO,WORLD19 return Map.put (E, PRESENT) ==null;20}21}22, class HashMap implements map, {public V P UT (K key, V value)-{//KEY=E=HELLO,WORLD27 28//See if the hash table is empty, if empty, open space if (table = = empty_table) {inflatetable (threshold); 32}33 34//Determine if the object is null35 if (key = = Nu LL) Putfornullkey return (value), PNs int hash = hash (key); Related to the Hashcode () method of the Object 39 40//Find the hash value in the hashtable int i = indexfor (hash, table.length); Try<k,v> e = table[i]; E! = null;  E = e.next) 43       {44//This time E is actually the first time the WORLD45 Object k;46 if (E.hash = = Hash && (k = e.key) = = Key | |                 Key.equals (k))) {OldValue = e.value;49 E.value = value;50 E.recordaccess (this); oldvalue;52 return//Walk here is actually no add element 53}54}5 5 modcount++;57 addentry (hash, key, value, I);     add element null;59}60 transient int hashseed = 0;62 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);}70-H ^= k.hashcode (); This is called the Hashcode () method of the object.//This function ensures, that hashcodes, differ only by74//constant Mul Tiples at each bit position has a bounded75//number of collisions (approximateLY 8 at default load factor). h ^= (H >>>) ^ (h >>> N); return h ^ (H &GT;&GT;&G T 7) ^ (H >>> 4); 78}79}

By looking at the source of the Add method, you know that this method relies on two methods: Hashcode () and Equals ().

The way to judge the uniqueness of an element: The element uniqueness is accomplished through the hashcode of the object and the Equals method

If an object has a different hashcode value, it is stored directly in the hash table without judging the Equals method.

If the hashcode value of the object is the same, determine again whether the object's Equals method is true.

If true, the same element is considered not saved. If False, it is stored as a different element.

If the class does not override both methods, the object () is used by default. Generally not the same.

17.05 HashSet Store custom objects and traverse

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 ("Xiaoming"), 8         hs.add (New Student ("Wang Choi"), 9         hs.add (New Student ("Wang Choi", 12)); 10         Hs.add (New Student ("Xiao Qiang"),         Hs.add (New Student ("Xiaoming"),         Hs.add (New Student ("Little Red", 22)); 13         Student s:hs         {             System.out.println (s.getname () + ":" +s.getage ());     }19}

17.06 HashSet guarantees the element uniqueness of the code embodiment

The repeating elements in the above example are stored in the collection because student does not override the Hashcode and Equals methods, the hashcode and Equals methods of the object () are used by default, and generally the results are not the same, so they are stored in the collection. The student class should override the Hashcode and Equals methods (auto-generated).

1 @Override 2 public     int hashcode ()  3     {4         final int prime = +; 5         int result = 1; 6         result = PR IME * result + age; 7         result = Prime * result + ((name = = null)? 0:name.hashcode ()); 8         return result; 9     }10     @Override12 C10/>public boolean equals (Object obj)-     {         if (this = = obj)             -return true;16         if (obj = = null) 17
   return false;18         if (getclass ()! = Obj.getclass ())             return false;20 Student Other         = (Student) obj;21< C19/>if (age! = other.age)             return false;23         if (name = = null) + (             other.name! = null)                 return false;27         } else if (!name.equals (other.name))             return false;29         return true;30     }

Overview and use of 17.07 Linkedhashset

Linkedhashset class Overview:

Elements are ordered and unique: the list guarantees that the elements are ordered and that the elements are unique by the hash table

Cases:

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");         String s:hs)         {             System.out.println (s);         }15     }16}

Operation Result:

Helloworldjava

17.08 TreeSet stores An integer type of element and traverses

TreeSet class overview: Use the natural order of the elements to sort the elements, or sort based on the Comparator provided when the set is created, depending on the construction method used.

Cases:

1 public class Practice  2 {3 public     static void Main (string[] args) 4     {5         treeset<integer> ts = new Treeset<integer> (); 6         Ts.add, 7         ts.add (8         ts.add), 9 Ts.add (+),         Ts.add (+),         Ts.add (24); 12         Ts.add (ts.add);         18 for         (Integer i:ts),         {             System.out.print (i+ ");         }19     }20}

Operation Result:

17.09 TreeSet to ensure the sequencing of elements in source code parsing

 1 interface Collection {...} 2 3 interface Set extends Collection {...} 4 5 interface Navigablemap {} 6 7 class Treema         P implements Navigablemap 8 {9 public V put (K key, V value) {one entry<k,v> t = root;12 if (t = = null) compare (key, key);//type (and possibly null) check15 root = NE         W entry<> (key, value, null); size = 1;18 modcount++;19 return null;20 }21 int cmp;22 entry<k,v> parent;23//Split comparator and comparable Paths24 Compa rator<?                 Super K> CPR = comparator;25 if (CPR! = null) 28 {29 Parent = t;30 CMP = cpr.compare (key, T.key), if (CMP < 0) + t = t                     . left;33 else if (cmp > 0) t = t.right;35 Else36 Return T.SetValue (value); PNS} while (t! = null);}39 else (key = null) New NullPointerException (); comparable<?                 Super k> K = (comparable<? super K>) key;44 do {= parent = t;47 CMP = K.compareto (T.key), if (CMP < 0)-T = t.left;50 El SE if (cmp > 0) t.right;52 t = else53 return T.setvalue (value         );}56} while (t! = null); entry<k,v> e = new entry<> (key, value, parent); 57 if (CMP < 0) Parent.left = e;59 Else60 parent.right = e;61 Fixafterin Sertion (e); size++;63 modcount++;64 return null;65}66}67-Class TreeSet implements Set 6  9 {navigablemap<e,object> Private transient m;71   TreeSet public () () (), (New Treemap<e,object> ()),}76, and public boolean add (E e) {m.put return (E, PRESENT) ==null;80}81}

The real comparison is dependent on the CompareTo () method of the element, and this method is defined in the comparable.

Therefore, to override this method, it is necessary to implement the comparable interface first. This interface represents a natural sort.

17.10 TreeSet guarantee Element uniqueness and natural ordering principles and plots

17.11 TreeSet storing custom objects and traversing Exercise 1

The student class implements the natural sort interface comparable, overriding the CompareTo () method

1 @Override2 public int compareTo (Student s) 3 {4     //main condition, rank by age 5     int num = this.age-s.age;6     //Minor condition, same age by name 7
   int num2 = (num = = 0)? This.name.compareTo (s.name): Num;8     return num2;9}

17.12 TreeSet storing custom objects and traversing Exercise 2

The student class implements the natural sort interface comparable, overriding the CompareTo () method

1 @Override 2 public int compareTo (Student s)  3 {4     //Main condition name length 5     int num = this.name.length ()-S.name.leng Th (); 6     //name is the same length, compare the contents of the name of the same 7     int num2 = num = = 0? this.name.compareTo (s.name): num; 8     //name is the same length and content, the comparison of the same age, the following Continue judging age 9     int num3 = Num2 = = 0? this.age-s.age:num2;10     return num3;11}

17.13 TreeSet guarantee Element uniqueness and comparator ordering principle and code implementation

1//Comparator sorting to make the collection comparable, anonymous inner class implementation 2 treeset<student> ts = new treeset<student> (New comparator<student> ()  3 {4     @Override 5 public     int compare (Student s1, Student S2)  6     {7         //Name length 8         int num = S1.get Name (). Length ()-s2.getname (). Length (); 9         //name content         int num2 = num = 0? s1.getname (). CompareTo (S2.getname ()): num;11         //age         int num3 = NUM2 = = 0? S1.getage ()-S2.getage (): num2;13         return num3;14     }15     16});

17.14 TreeSet Summary of the ordering of elements

Uniqueness: Based on the comparison of whether the returned is determined by the

Sort: 1. Natural sorting, the elements of a class that want to be naturally ordered must implement the natural sort interface comparable (elements are comparable)

2. Comparator ordering, let the collection's construction method receive a comparer interface subclass Object Comparator (collection is comparative)

17.15 Generate 10 x 1-20 random number required random number cannot repeat case concise version

Write a program that gets 10 random numbers from 1 to 20, requiring random numbers to not be duplicated.

1 public class Practice  2 {3 public     static void Main (string[] args) 4     {5         //Create random Number Object 6         random r = new Random (); 7  8         //Create a set Set 9         hashset<integer> ts = new hashset<integer> ();/         /Determine if the set length is less than 1012 While         (Ts.size () <)         {             + int num = R.nextint (+) + 1;15             ts.add (num);         }17         //Traverse Set set for         (Integer i:ts) 20
   {21             System.out.println (i);         }23     }24}

17.16 Keyboard entry Student information sorted by total score output in console case

Student class

 1 public class Student 2 {3 private String name, 4 private int Chinese; 5 private int math; 6 Private in T 中文版; 7 Public Student (String name, int Chinese, int math, int 中文版) 8 {9 super (); this.name = NA me;11 This.chinese = chinese;12 This.math = math;13 this.english = english;14}15 public S Tring GetName () () {name;18}19 public void SetName (String name), This.nam E = name;22}23 public int Getchinese (), {chinese;26}27 public void Setchinese      T Chinese) {This.chinese = chinese;30}31 public int Getmath () + {math;34     }35 public void Setmath (int math) $ {PNS This.math = math;38}39 public int getenglish () 40 {$ return english;42}43 public void setenglish (int 中文版) * This.english = 中文版  ; 46}47   $ public int Getsum () $ {this.chinese+this.english+this.math;51}52} 

Test class

 1 public class Practice 2 {3 public static void main (string[] args) 4 {5 treeset<student> ts = n EW treeset<student> (New comparator<student> () 6 {7 @Override 8 public int Co Mpare (Student s1, Student S2) 9 {10//By total score comparison int num1 = S2.getsum ()-S1.get                 Sum (); 12//Total score comparison by language score int num2 = Num1==0?s1.getchinese ()-S2.getchinese (): num1;14 Chinese results are the same according to the mathematical results of the comparison of int num3 = Num2==0?s1.getmath ()-S2.getmath (): num2;16//Number of studies                 The same performance by English score comparison of num4 = Num3==0?s1.getchinese ()-S2.getchinese (): num3;18//English score by name comparison 19             int num5 = Num4==0?s1.getname (). CompareTo (S2.getname ()): num4;20 return num5;21 }22}); (int i = 1; I <= 5; i++): {Scanner sc = new Scanner (system.in); System.ouT.println ("Please enter the name of the student" +i+ "); String name = Sc.nextline (); System.out.println (" Please enter the language of the "+i+" students Score "); String Chinese = sc.nextline (); System.out.println (" Please enter the math score of the student "+i+"); Tring math = Sc.nextline (); System.out.println ("Please enter the" +i+ "Student's English score"); INE (); Student s = new Student (name, Integer.parseint (Chinese), integer.parseint (math), Integ Er.parseint (English)); Ts.add (s), PNS}38 System.out.println ("Student Information"); SYSTEM.OUT.P Rintln ("name \ t language \ t math \ t english \ t total score"); Max for (Student s:ts): {System.out.println (S.getname () + "\ T" +s. Getchinese () + "\ T" +s.getmath () + "\ T" +s.getenglish () + "\ T" +s.getsum ()); 43}44}45}

Operation Result:

Javase Learning Summary 17th Day _ Collection Frame 3

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.