Java EE Fundamentals (17)/collections

Source: Internet
Author: User
Tags addall comparable sorted by name

1. Set Frame (HashSet store string and Traverse)
    • A:set Collection Overview and Features
      • View by API
    • B: Case Demo

      • HashSet Store strings and traverse
      • HashSet<String> hs = new HashSet<>();boolean b1 = hs.add("a");boolean b2 = hs.add("a");           //当存储不成功的时候,返回falseSystem.out.println(b1);System.out.println(b2);for(String s : hs) {    System.out.println(s);}
2. Set FRAME (HashSet store custom object guarantees element Uniqueness)
    • A: Case Demo

      • Stores custom objects and guarantees element uniqueness.

        HashSet<Person> hs = new HashSet<>();hs.add(new Person("张三", 23));hs.add(new Person("张三", 23));hs.add(new Person("李四", 23));hs.add(new Person("李四", 23));hs.add(new Person("王五", 23));hs.add(new Person("赵六", 23));
    • Overriding the Hashcode () and Equals () methods
3. Set FRAME (HashSet store custom objects to ensure element uniqueness and code optimization)
    • A: Drawing Demo
      • Drawing description Comparison Process
    • B: Code optimization
      • To reduce comparisons, optimize the hashcode () code notation.
      • The final version is automatically generated.
4. Set FRAME (how HashSet guarantees element uniqueness)
    • 1.HashSet principle
      • We use set sets are all need to remove duplicate elements, if at the time of storage by equals () comparison, low efficiency, hashing algorithm to improve the efficiency of de-duplication, reduce the number of times using the Equals () method
      • When HashSet calls the Add () method to store the object, it first calls the object's Hashcode () method to get a hash value, and then finds in the collection whether there are objects of the same hash value
        • If no object with the same hash value is deposited directly into the collection
        • If there is an object with the same hash value, the Equals () comparison is performed on the same object as the hash value, and the result of the comparison is false to deposit, true does not exist
    • 2. Save the object of the custom class in HashSet to repeat
      • The hashcode () and Equals () methods must be overridden in a class
      • Hashcode (): The same object return value must be the same as the property, the return value of different properties is as different as possible (improve efficiency)
      • Equals (): property returns True only if the property is different, returns false, and returns false when the store
5. Collection Framework (overview and use of Linkedhashset)
    • Features of A:linkedhashset
    • B: Case Demo
      • Features of Linkedhashset
        • You can make sure how you save it.
6. Set FRAME (Generate 10 1-20 random number requires random number cannot be duplicated)
    • A: Case Demo

      • Requirement: Write a program that gets 10 random numbers from 1 to 20, requiring random numbers to not be duplicated. and output the final random number to the console.
      • HashSet<Integer> hs = new HashSet<>();      //创建集合对象Random r = new Random();                    //创建随机数对象while(hs.size() < 10) {    int num = r.nextInt(20) + 1;            //生成1到20的随机数    hs.add(num);}for (Integer integer : hs) {                //遍历集合    System.out.println(integer);            //打印每一个元素}
7. Set FRAME (practice)
    • Use scanner to read a line of input from the keyboard, remove the repeated characters, and print out the different characters

      • Aaaabbbcccddd

        Scanner sc = new Scanner(System.in);            //创建键盘录入对象System.out.println("请输入一行字符串:");String line = sc.nextLine();                    //将键盘录入的字符串存储在line中char[] arr = line.toCharArray();                //将字符串转换成字符数组HashSet<Character> hs = new HashSet<>();        //创建HashSet集合对象for(char c : arr) {                             //遍历字符数组    hs.add(c);                                  //将字符数组中的字符添加到集合中}for (Character ch : hs) {                       //遍历集合    System.out.println(ch);}
8. Set FRAME (practice)
    • removes duplicate elements from the collection
    •   public static void Main (string[] args) {arraylist<string> lis        t = new arraylist<> ();        List.add ("a");        List.add ("a");        List.add ("a");        List.add ("B");        List.add ("B");        List.add ("B");        List.add ("B");        List.add ("C");        List.add ("C");        List.add ("C");        List.add ("C");        SYSTEM.OUT.PRINTLN (list);        System.out.println ("After removing duplicates:");        Getsingle (list);    SYSTEM.OUT.PRINTLN (list); }/* * Remove duplicate elements from the collection * 1,void * 2,list<string> list */public static void Getsingle (List<stri        Ng> list) {linkedhashset<string> LHS = new linkedhashset<> ();                                   Lhs.addall (list);                                       Adds all the elements in the list collection to LHS list.clear ();                                   Empty the original set List.addall (LHS); Add removed duplicate elements back to list}  
9. Set FRAME (treeset store integer type elements and Traverse)
    • A: Case Demo
      • TreeSet stores an integer type of element and traverses
10. Collection Framework (TreeSet store custom objects)
    • A: Case Demo
      • Store Person Object
11, set FRAME (TreeSet guarantee element unique and natural sort of principle and diagram)
    • A: Drawing Demo
      • TreeSet principle and plot to guarantee the unique and natural ordering of elements
12. Collection Framework (TreeSet store custom objects and traverse Exercise 1)
    • A: Case Demo
      • TreeSet Store custom objects and traverse Exercise 1 (Sort by name)
13. Collection Framework (TreeSet store custom objects and traverse Exercise 2)
    • A: Case Demo
      • TreeSet Store custom objects and traverse Exercise 2 (sorted by name)
14, set framework (TreeSet guarantee element unique and comparator sorting principle and code implementation)
    • A: Case Demo
      • TreeSet principle and code implementation of guaranteed element uniqueness and comparator ordering
15. Set FRAME (TreeSet principle)
    • 1. Features
      • TreeSet are used for sorting, you can specify a sequence in which the objects are stored in the order specified
    • 2. How to use
      • A. Natural order (comparable)
        • The Add () method of the TreeSet class promotes the stored object to the comparable type
        • The CompareTo () method of the calling object and the object comparison in the collection
        • Stored according to the results returned by the CompareTo () method
      • B. Comparator order (Comparator)
        • Create a treeset when you can make a comparator
        • If a subclass object of comparator is passed in, the TreeSet is sorted in the order of the comparator
        • The Add () method internally calls the Compare () method in the comparator interface to sort
        • The object being called is the first parameter of the Compare method, and the object in the collection is the second parameter of the Compare method
      • C. Two different ways of difference
        • TreeSet constructors do not pass anything, by default in the order of comparable in the class (no error ClassCastException)
        • TreeSet if the comparator is passed in, priority is given to comparator
16. Set FRAME (practice)
  • Stores unordered and duplicated strings in a collection, defines a method to be ordered (dictionary order), and does not remove duplicates

        public static void Main (string[] args) {arraylist<string> list = new arraylist<> ();        List.add ("CCC");        List.add ("CCC");        List.add ("AAA");        List.add ("AAA");        List.add ("BBB");        List.add ("ddd");        List.add ("ddd");        Sort (list);    SYSTEM.OUT.PRINTLN (list); }/* * Sort the elements in the collection and keep repeating * 1,void * 2,list<string> List */public static void sort (List<strin G> list) {treeset<string> ts = new treeset<> (new comparator<string> () {//define comparer (new Com                      Parator () {} is a subclass object of comparator) @Override public int Compare (string s1, string s2) {                                 Override the Compare method int num = S1.compareto (s2); Compare content return num = = 0?                                  1:num;        If the content returns a number that is not 0}});                                                    Ts.addall (list); Sets the listAdd all the elements in the TS to List.clear ();                                                    Empty list list.addall (TS); Sorting in TS and preserving duplicate results in Add to list}
17. Set FRAME (practice)
    • Receives a string from the keyboard, the program sorts all the characters in it, such as keyboard input: Helloitcast program printing: ACEHILLOSTT

      Scanner sc = new Scanner(System.in);            //创建键盘录入对象System.out.println("请输入一行字符串:");String line = sc.nextLine();                    //将键盘录入的字符串存储在line中char[] arr = line.toCharArray();                //将字符串转换成字符数组TreeSet<Character> ts = new TreeSet<>(new Comparator<Character>() {    @Override    public int compare(Character c1, Character c2) {        //int num = c1.compareTo(c2);        int num = c1 - c2;                  //自动拆箱        return num == 0 ? 1 : num;    }});for(char c : arr) {    ts.add(c);}for(Character ch : ts) {    System.out.print(ch);}
18. Set FRAME (practice)
    After the
    • Program starts, you can receive multiple integers from the keyboard input until you end the input when you enter quit. Prints all input integers in reverse order. Scanner sc = new Scanner (system.in); Create keyboard Entry Object System.out.println ("Please enter:"); Treeset ts = new Treeset<> (new Comparator () {//constructor method passed to TreeSet by the comparer

        @Override Public                    int compare (integer i1, integer i2) {//int num = i2-i1;            automatic unpacking int num = I2.compareto (i1); return num = = 0?        1:num;    }    });            while (true) {String line = Sc.nextline ();            Store the keyboard input string in line if ("Quit"). Equals (line))//If the string constant and the variable are compared, the constants are preceded so that null pointer exceptions do not occur, and the variables may store nulls        Break       try {int num = Integer.parseint (line);        Converts a numeric string into a digital ts.add (NUM);        } catch (Exception e) {System.out.println ("The data you entered is wrong, please enter an integer");    }} for (Integer i:ts) {//Traversal TreeSet collection System.out.println (i); }
19, set frame (keyboard input student information according to the total score sorted after output in the console)
    • A: Case demonstration

      • Requirements: Keyboard input 5 Student information (name, language score, Math score, English score), according to the total score from high to low output to the console. Scanner sc = new Scanner (system.in); System.out.println ("Please enter 5 student grades are: (Name, language score, Math score, English score)"); Treeset ts = new Treeset<> (new Comparator () {@Override public int compare (Student s1, Student s2) {int num = S2.getsum ()-s1.getsum (); Sort return num = 0 According to the student's overall grade? 1:num; } });

          while (Ts.size () < 5) {String line = Sc.nextline ();        try {string[] arr = Line.split (",");             int Chinese = integer.parseint (arr[1]);                Convert language score int math = Integer.parseint (arr[2]);             Convert math score int 中文版 = Integer.parseint (arr[3]);    Convert English scores ts.add (new Student (Arr[0], Chinese, math, 中文版));    } catch (Exception e) {System.out.println ("the input format is incorrect, enter 5 student performance formats: (Name, language score, Math score, English score"); }}system.out.println ("Ranked student scores are:"); for (Student s:ts) {System.out.println (s);}  
20. Summary
    • 1.List
      • A. Normal for loop, using get ()
      • B. Call the iterator () method to get iterator, using the Hasnext () and Next () methods
      • C. Enhance for loop, as long as the class that can use iterator can be used
      • The D.vector collection can use the enumeration hasmoreelements () and Nextelement () methods
    • 2.Set
      • A. Call the iterator () method to get iterator, using the Hasnext () and Next () methods
      • B. Enhance the For loop, as long as the class that can use iterator can be used
    • 3. Normal for loop, iterator, enhance whether the for loop can be removed during traversal

Java EE Fundamentals (17)/collections

Related Article

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.