Java learning plan 07: collections, generics

Keywords: Java Back-end

catalogue

  • Collection
  • List
  • Set
  • generic paradigm
  • Map
  • Collections

Collection

  • Collection is the top-level interface of a singleton collection. It represents a set of objects, which are also called collection elements.
  • JDK does not any direct implementation of this interface of the question bank, but provides more specific implementation of sub interfaces (such as Set and List)

Create an object for the Collection

  • Polymorphic mode
  • The specific implementation class arrayList
Method nameexplain
add(E e)Add element
remove(Object o)Removes the specified element from the collection
void clear()Empty elements in collection
contains(Object o)Determines whether the specified element exists in the collection
isEmpty()Determine whether the collection is empty
int size()The length of the set, that is, the number of elements in the set

Iterator: iterator

Special traversal mode of collection

 //Create collection object
Collection<String> c = new ArrayList<String>();
//Get iterator method
Iterator<String> it = c.iterator();
  • Iterator iterator(); Returns the iterator of the elements in this collection, which is obtained through the iterator () method of the collection
  • The iterator is obtained through the iterator() method of the collection, so we say that it depends on the collection

Common methods in Iterator:

  • E next(): returns the next element in the iterator
  • hasNext(): returns true if the iteration has more elements

Code demonstration

public class CollectionDemo02 {
    public static void main(String[] args) {
        //Create collection object
        Collection<String> c = new ArrayList<String>();
        //Add (E) add element
        c.add("hello");
        c.add("world");
        c.add("java");
        //Get iterator method
        Iterator<String> it = c.iterator();
        //The while loop determines whether there is an element in it.hasNext(), and if there is an output element
        while (it.hasNext()){
            String s = it.next();
            System.out.println(s);
        }
    }
}

Case: the Collection collection stores the student object and traverses it

Requirements: create a collection of student objects, store 3 student objects, and traverse

//Test student class
public class TestStudent {
    public static void main(String[] args) {
        //Create collection collection object
        Collection<Student> student = new ArrayList<Student>();
        //Create student object
        Student s1 = new Student("Zhao lele",20);
        Student s2 = new Student("Li leilei",22);
        Student s3 = new Student("Mei Mei Han",19);
        //Add students to collection
        student.add(s1);
        student.add(s2);
        student.add(s3);
        //Traversal set
        Iterator<Student> it = student.iterator();
        while (it.hasNext()){
            Student s = it.next();
            System.out.println("full name:"+s.getName()+",Age:"+s.getAge());
        }
    }
}
//Student class
public class Student {
    private String name;
    private int age;
    public Student() {
    }
    public Student(String name,int age){
        this.name = name;
        this.age = age;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public int getAge() {
        return age;
    }

    public void setAge(int age) {
        this.age = age;
    }
}

List

List collection overview

  • An ordered set (also known as a sequence), in which the user can accurately control the insertion position of each element in the list. Users can access elements through integer indexes and search for elements in the list.
  • Unlike Set collections, lists usually allow duplicate elements.

List set features:

  • Ordered: the stored and retrieved elements are in the same order
  • Repeatable: stored elements can be repeated

List collection specific methods

Method nameexplain
void add(int index,E element)The specified position in this collection exceeds the specified element
remove(int index)Deletes the element at the specified index and returns the deleted element
set(int index,E element)Modify the element at the specified index and return the modified element
get(int index)Returns the element at the specified index

Case: the List collection stores student objects and traverses * * (three ways: iterator traversal, for loop and for each traversal)**

Requirements: create a collection of student objects, store 3 student objects, and traverse

The Student class is the same as the Collection class above. Instead of writing a small series, you can directly write the TestList class, mainly to practice and master two traversal methods.

public class TestList {
    public static void main(String[] args) {
        //Create a List collection object
        List<Student> student =new ArrayList<Student>();
        //Create student object
        Student s1 = new Student("Zhao lele",20);
        Student s2 = new Student("Li leilei",22);
        Student s3 = new Student("Mei Mei Han",19);
        //Add students to collection
        student.add(s1);
        student.add(s2);
        student.add(s3);
        //Iterator traversal
        Iterator<Student> it = student.iterator();
        while (it.hasNext()){
            Student s = it.next();
            System.out.println("full name:"+s.getName()+"Age:"+s.getAge());
        }
         System.out.println("--------------------------");
       //for loop mode
        for (int i = 0; i < student.size(); i++) {
            Student s =student.get(i);
            System.out.println("full name:"+s.getName()+"Age:"+s.getAge());
        }
         System.out.println("--------------------------");
        //for each traversal
        for (Student s:student) {
            System.out.println("full name:"+s.getName()+"Age:"+s.getAge());
        }
    }
}

Concurrent modification exception

//ConcurrentModificationException

Cause

  • In the process of iterator traversal, the length of the elements in the set is modified through the set object, resulting in the inconsistency between the expected modified value and the actual modified value in the elements obtained by the iterator

Solution

  • Use the for loop to traverse, and then use the collection object to do the corresponding operation

ListIterator: list iterator

  • It is obtained through the listIterator() method of the List collection, so it is a unique iterator of the List collection

  • A list iterator that allows the programmer to traverse the list in either direction, modify the list during the iteration, and get the current position of the iterator in the list

Common methods in ListIterator

  • E next(): returns the next element of the iterator
  • hasNext(): returns true if the iteration has more elements
  • E previous(): returns the previous element in the list
  • hasPrevious(): returns true if the list iterator traverses the list in the opposite direction with more elements
  • void add (E): inserts the specified element into the list

Characteristics of List set subclass

Common subclasses of List collection: ArrayList, LInkedList

  • ArrayList: the underlying data structure is an array, with fast query and slow addition and deletion
  • LinkedList: the underlying data structure is a linked list. The query is slow and blocks are added or deleted

ArrayList and LinkedList traverse array elements in three ways, respectively

public class LinkedList {
    public static void main(String[] args) {
        //Create collection object
        ArrayList<String> array = new ArrayList<String>();
        array.add("hello");
        array.add("world");
        array.add("java");
        System.out.println("ArrayList Three traversal modes");
        //for each traversal
        System.out.println("for each ergodic");
        for (String s:array) {
            System.out.println(s);
        }

        //for loop traversal
        System.out.println("for Loop traversal");
        for (int i = 0; i < array.size(); i++) {
            String s = array.get(i);
            System.out.println(s);
        }
        //Iterator traversal
        System.out.println("Iterator traversal");
        Iterator<String> it = array.iterator();
        while (it.hasNext()){
            String s = it.next();
            System.out.println(s);
        }
        System.out.println("----------------------------");
        System.out.println("LinkedList Three traversal modes");
        java.util.LinkedList<String> linkedList= new java.util.LinkedList<>();
        linkedList.add("hello");
        linkedList.add("world");
        linkedList.add("java");
        //for each traversal
        System.out.println("for each ergodic");
        for (String s:linkedList) {
            System.out.println(s);
        }

        //for loop traversal
        System.out.println("for Loop traversal");
        for (int i = 0; i < linkedList.size(); i++) {
            String s = linkedList.get(i);
            System.out.println(s);
        }
        //Iterator traversal
        System.out.println("Iterator traversal");
        Iterator iterator =linkedList.iterator() ;
        while (iterator.hasNext()){
            String s1 = (String) iterator.next();
            System.out.println(s1);
        }

    }
}

Comparison of adding 10000 elements between LinkedList and ArrayList

import java.util.ArrayList;
import java.util.List;
import java.util.LinkedList;
public class LinkedListDemo01 {
    public static void main(String[] args) {
        List<String> LList = new LinkedList<String>();
        List<String> AList = new ArrayList<String>();
        long startTime = System.currentTimeMillis();
        for (int i = 0; i < 10000; i++) {
            LList.add(""+i);
        }
        long endTime = System.currentTimeMillis();
        long result = endTime - startTime;
        System.out.println("LinkedList Add time consuming:"+result);
        for (int i = 0; i < 10000; i++) {
            AList.add(""+i);
        }
        endTime = System.currentTimeMillis();
        result=endTime = startTime;
        System.out.println("ArrayList Add time consuming:"+result);
    }
}

Set

Set set features

  • A collection that does not contain duplicate elements
  • Without an indexed method, you can't use a normal for loop to traverse
  • There is no guarantee for the iterative order of the set, and the order of saving, storing and fetching is not the same

Hash value

Hash value: it is a value of int type calculated by JDK according to the address, string or number of the object

There is a method in the Object class to get the hash value of the Object

  • public int hashCode(): returns the hash code value of the object

Characteristics of hash value of object:

  • By default, different objects have different hashcode () values
  • Through method rewriting, you can realize that the hash values of different objects are the same

HashSet

HashSet set features

  • Inherit Set characteristics
  • The underlying data structure is a hash table

HashSet sets store elements. To ensure element uniqueness, you need to override hashCode() and equals()

//Override hashCode() equals()
@Override
public boolean equals(Object o) {
    if (this == o) return true;
    if (o == null || getClass() != o.getClass()) return false;
    Student student = (Student) o;
    return age == student.age && Objects.equals(name, student.name);
}

@Override
public int hashCode() {
    return Objects.hash(name, age);
}

Hashtable

  • Before JDK8, the bottom layer was implemented by array + linked list, which can be said to be an array with linked list elements
  • After JDK8, when the length is long, the bottom layer is optimized

LinkedHashSet

  • The Set interface implemented by hash table and linked list has predictable iteration order
  • There is a linked list to ensure the order of elements, that is, the storage and extraction order of elements are consistent
  • There is a hash table to ensure that the elements are unique, that is, there are no duplicate elements

Code demonstration

public class LinkedHashSetDemo {
    public static void main(String[] args) {
        LinkedHashSet<String> linkedHashSet = new LinkedHashSet<String>();
        linkedHashSet.add("hello");
        linkedHashSet.add("world");
        linkedHashSet.add("java");
        linkedHashSet.add("world");//Repeating element
        for (String s:linkedHashSet) {
            System.out.println(s);
        }
    }
}

TreeSet

  • Elements are ordered. The order here does not refer to the order of storage and retrieval, but is sorted according to certain rules. The specific sorting method depends on the construction method
    • TreeSet(): sort according to the natural order of its elements
    • TreeSet (comparator): sort according to the specified comparator
  • There is no indexed method, so you can't use a normal for loop to traverse
  • A collection that does not contain duplicate elements because it is a Set collection

Use of natural sorting Comparable

  • Store and traverse the student object, create a TreeSet collection, and use the parameterless construction method
  • Requirements: sort according to the age from small to large. If the age is the same, sort according to the alphabetical order of the name
public class Student implements Comparable<Student>  {
    private String name;
    private int age;

    public Student() {
    }
    public Student(String name,int age){
        this.name=name;
        this.age=age;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public int getAge() {
        return age;
    }

    public void setAge(int age) {
        this.age = age;
    }

    @Override
    public int compareTo(Student s) {
//        return 0;
//        return 1;
//        return -1;
//        From small to large according to age
//        int num =s.age- this.age; / / descending
          int num = this.age-s.age;//Ascending order
          //When the age is the same, in ascending alphabetical order
          int num2 =  num==0?this.name.compareTo(s.name):num;
          return num2;
    }
}
import java.util.TreeSet;public class TreeSetComparable {    public static void main(String[] args) {        //Create a collection object TreeSet < student > TS = new TreeSet < student > (); Student s1 = new Student("diaochan",22);         Student s2 = new Student("wangzhaojun",24);         Student s3 = new Student("yangyuhuan",20);         Student s4 = new Student("xishi",23);         Student s5 = new Student("wangsimin",23);         ts.add(s1);         ts.add(s2);         ts.add(s3);         ts.add(s4);         ts.add(s5);         for (Student s:ts) {            System.out.println(s.getName()+s.getAge());        }    }}

conclusion

  • The TreeSet collection is used to store custom objects. The parameterless construction method uses natural sorting to sort elements
  • Natural sorting is to make the column to which the element belongs implement the Comparable interface and override the comparaTo(To) method
  • The rewriting method is to pay attention to that the sorting rules must be written according to the required Zhu ah yo conditions and secondary conditions

Case: write a program to obtain 10 random numbers between 1-20. It is required that the random numbers cannot be repeated and output on the console.

import java.util.HashSet;import java.util.Random;import java.util.Set;import java.util.TreeSet;public class TreeSetDemo02 {    public static void main(String[] args) {        //1. Create a set / / set < integer > set = new HashSet < integer > ()// Unordered set < integer > set = new TreeSet < integer > ()// Orderly / / 2. Create random number object random r = new random()// 3. Judge whether the set length is less than 10 while (set. Size() < 10) {/ / generate a random number and add it to the set int number = r.nextint (20) + 1; set. Add (number);} / / traverse the set for (integer I: Set) {system. Out. Println (I);}}}

generic paradigm

Genericity: a feature introduced in JDK5, it provides a compile time type safety detection mechanism, which allows illegal types to be detected at compile time

Its essence is parameterized type, that is, the data type operated on is specified as a parameter

When referring to parameters, the most familiar thing is that there is a formal parameter when defining the method, and then the arguments are passed when the submethod is called. So what about parameterized types?

As the name suggests, it is to parameterize the type from the original specific type, and then pass in the specific type when using / calling

Generic definition format:

  • < type >: Specifies the format of a type. The type here can be seen from the forming parameters
  • < L type 1, type 2,... >: specify multiple types of formats separated by commas. The type here can be regarded as a formal parameter
  • In the future, the given type can be regarded as an argument, and the type of the argument can only be a reference data type.

Benefits of generics:

  • Class member variable data can be specified when creating objects

  • Advance the run-time problem to compile time

  • Casts are avoided

Generic class

Definition format of generic class:

  • Modifier class class name < type > {}
  • public class Generic{}
    • T here can be arbitrarily written as any identifier. Common parameters such as t, E, K, V, etc. are commonly used with generic identifiers
//Generic class
public class Generic <T>{
    private T t;

    public T getT() {
        return t;
    }

    public void setT(T t) {
        this.t = t;
    }
}
//Use of generic classes
Generic<String> g1 = new Generic<String>();
g1.setT("Zhao leilei");
System.out.println(g1.getT());
Generic<Integer> g2 = new Generic<Integer>();
g2.setT(30);
System.out.println(g2.getT());

generic method

  • Format: modifier < type > return value type method name (type variable name) {}
  • public void show(T t){}

Generic method definition

//generic method 
public class GenericDemo01{
    public <T> void show(T t){
        System.out.println(t);
    }
}

Generic method usage

GenericDemo01 g1 = new GenericDemo01();
g1.show("Li leilei");
g1.show(30);
g1.show(true);
g1.show(12.33);

generic interface

  • Format: modifier interface interface name < type > {}
  • Example: public interface Generic {}

Code demonstration

Generic interface definition

public interface Generic<T>{
    void show(T t);
}

Classes that implement generic interface methods

public class Genericlmpl<T> implements Generic<T> {

    @Override
    public void show(T t) {
        System.out.println(t);
    }
}

Test class

public class GenericDemo {
    public static void main(String[] args) {
        Generic<String> g1 = new Genericlmpl<String>();
        g1.show("Li leilei");
        Generic<Integer> g2 = new Genericlmpl<Integer>();
        g2.show(12);

    }
}

Type wildcard

To represent the parent classes of various generic lists, you can use type wildcards

  • Type wildcard: <? >
  • List< ?>: Represents a list whose element type is unknown, and its elements can match any type
  • This List with wildcards only indicates that it is the parent of various generic lists, and cannot add elements to it

If we don't want List <? > Is the parent class of any generic List. You only want it to represent the parent class of a generic List. You can use the upper limit of type wildcards

  • Upper limit of type wildcard: <? Extensions type >
  • List<? Extensions Number >: the type it represents is Number or its subtype-
  • The upper limit of a type wildcard is the highest type that can be defined
 //Upper limit of type wildcard
//        List<? extends Number> list4 = new ArrayList<Object>();
        List<? extends Number> list4 = new ArrayList<Integer>();

In addition to specifying the upper limit of type wildcards, we can also indicate the lower limit of type wildcards

  • Type wildcard lower limit: <? super type >

  • List<? Super Number >: the type it represents is Number or its parent type

  • The lower bound of the type wildcard is the lowest type that can be defined

 //Lower bound of type wildcard
        List<? super Number> list5 = new ArrayList<Object>();
        List<? super Number> list6 = new ArrayList<Number>();
//        List<? super Number> list7 = new ArrayList<Integer>();
    }

Variable parameters

Variable parameters are also called variable number of parameters. If they are used as formal parameters of a method, the number of method parameters is variable

  • Format: modifier return value type method name (data type... Variable name) {}
  • Example: public static int sum(int... a) {}

Precautions for variable parameters

  • The variable here is actually an array
  • If a method has multiple parameters, including variable parameters, the variable parameters should be placed last

Variable parameter summation code demonstration

public class ArgsDemo01 {
    public static void main(String[] args) {
        System.out.println(sum(10,30,40,50,60));
        System.out.println(sum(10,30));
        System.out.println(sum(10,2,3,3,5,60));
    }
    public static int sum(int...a){
     int sum = 0;
        for (int i : a) {
            sum += i;
        }
        return sum;
    }
}

Map

  • Interface map < K, V > k: type of key; 5: Type of value
  • Objects that map keys to values; Cannot contain duplicate keys; Each key can be mapped to a maximum of one value
  • Give an example of the student's student number and name
    • Li leilei
    • ineia002 Zhao Jingjing
    • ineia003 Wang lele

Create an object for the Map collection

  • Polymorphic way
  • The specific implementation class is HashMap

Basic functions of Map collection

Method nameexplain
put(K key,V value)Add element
remove(Object key)Delete the element corresponding to the key value according to the key
void clear()Remove all key value pair elements
containsKey(Object key)Determines whether the collection contains the specified key
containsValue(Object value)Determines whether the collection contains the specified value
isEmpty()Determine whether the collection is empty
int size()The length of the set, that is, the number of key value pairs in the set
get(Object key)Get value according to key
map.keySet()Gets a collection of all keys in the array
map.values()Gets the collection of all values in the array
map.entrySet()Gets a collection of all key value pairs

Two methods of traversing map sets

public class MapDemo03 {
    public static void main(String[] args) {
        Map<String,String> map = new HashMap<String,String>();
        map.put("zhang wuji","Zhao Min");
        map.put("Guo Yang","little dragon maiden");
        map.put("Guo Jing","Huang Rong");
        Set<String> KeySet = map.keySet();
        for (String k:KeySet) {
            String value = map.get(k);
            System.out.println(k +value);
        }
    }
}
public class MapDemo04 {
    public static void main(String[] args) {
        Map<String,String> map = new HashMap<String,String>();
        map.put("zhang wuji","Zhao Min");
        map.put("Guo Yang","little dragon maiden");
        map.put("Guo Jing","Huang Rong");
        //Gets a collection of all key value pair objects
        Set<Map.Entry<String, String>> enTrySet = map.entrySet();
        //Traverse all key value pair objects to get each object
        for (Map.Entry<String, String> ma:enTrySet) {
            //Get keys and values for objects based on key values
            System.out.println(ma.getKey()+ma.getValue());
        }

    }
}

Counts the number of occurrences of each character in the string

For example, enter "aababcacdabcde" on the keyboard and output: a(5)b(4)c(3)d(2)e(1) on the console

import java.util.HashMap;
import java.util.Scanner;
import java.util.Set;

public class MapDemo07 {
    public static void main(String[] args) {
        //Enter a string on the keyboard
        Scanner scanner = new Scanner(System.in);
        System.out.println("Please enter a string:");
        String line = scanner.nextLine();
        //Create a HashMap collection with the key Character and the value Integer
        HashMap<Character,Integer> hm = new HashMap<Character,Integer>();
        //Traverse the string to get each character
        for (int i = 0; i < line.length(); i++) {
            char key = line.charAt(i);
            //Take each character as a key to find the corresponding value in the HashMap collection and see its return value
            Integer value = hm.get(key);
            if (value == null){
                //If the return value is null, it indicates that the character does not exist in the HashMap collection. The character is used as a key and 1 as a stored value
                hm.put(key,1);
            }else{
                value++;
                hm.put(key,value);
            }
        }
        //Traverse the HashMap set to get the keys and values, and splice them as required
        StringBuilder sb = new StringBuilder();
        Set<Character> keySet = hm.keySet();
        for (Character key:keySet) {
            Integer value = hm.get(key);
            sb.append(key).append("(").append(value).append(")");
        }
        String result =sb.toString();
        //Output results
        System.out.println(result);
    }
}

Collections

Overview of the Collections class

  • Is a tool class for collection operations

Common methods of Collections class

  • Sort (list): sort the specified list in ascending order

  • Reverse (list <? > list): reverses the order of elements in the specified list

  • Shuffle (list <? > list): randomly arrange the specified list using the default random source

Posted by theex on Thu, 11 Nov 2021 14:31:17 -0800