Collection, generic, List, Collections, Set, Map

Collection, generic, List, Collections, Set, Map

1, Collection collection

1.1 collection overview

Collection: a collection is a container provided in java that can be used to store multiple data.

Differences between sets and arrays:

  • The length of the array is fixed. The length of the collection is variable.
  • The elements of the same type are stored in the array, and any type of data can be stored. Collections store reference data types. If you want to store basic type data, you need to store the corresponding packaging type
1.2 inheritance relationship of common classes of collection

Collection: the root interface of a single column collection class. It is used to store a series of elements that conform to certain rules. It has two important sub interfaces, namely Java util. List and Java util. Set .

List is characterized by ordered elements and repeatable elements; The main implementation classes of the list interface are Java util. ArrayList and Java util. LinkedList

Set is characterized by disordered and unrepeatable elements. The main implementation classes of the set interface are Java util. HashSet and Java util. LinkedHashSet .

[external chain picture transfer failed. The source station may have anti-theft chain mechanism. It is recommended to save the picture and upload it directly

[external chain picture transfer failed. The source station may have anti-theft chain mechanism. It is recommended to save the picture and upload it directly
Note: this figure is only our common sets. These sets do not mean that there are only these sets.

The Collection itself is a tool, which is stored in Java Util package. The Collection interface defines the most common content in the single column Collection framework.

1.3 common functions of colletion [ key points ]

Collection is the parent interface of all single column collections. Therefore, some common methods for single column collections (List and Set) are defined in collection, which can be used to operate all single column collections. The method is as follows:

  • Public Boolean add (E): adds the given object to the current collection.
  • public void clear(): clear all elements in the collection.
  • Public Boolean remove (E): deletes the given object from the current collection.
  • public boolean contains(Object obj): determines whether the current collection contains a given object.
  • public boolean isEmpty(): judge whether the current collection is empty.
  • public int size(): returns the number of elements in the collection.
  • public Object[] toArray(): store the elements in the collection into an array

2, Iterator iterator

Iteration: that is, the general acquisition method of Collection elements. Before taking an element, first judge whether there is an element in the set. If so, take out this element and continue to judge. If there is any, take it out again. Always take out all the elements in the Collection. This extraction method is called iteration in technical terms.

2.1 Iterator interface

The common methods of Iterator interface are as follows: [key points]

  • public E next(): returns the next element of the iteration.

  • public boolean hasNext(): returns true if there are still elements that can be iterated.

public class IteratorDemo { 
    public static void main(String[] args) { 
        // Create objects using polymorphism 
        Collection<String> coll = new ArrayList<String>(); 
        // Add element to collection 
        coll.add("String of stars");
        coll.add("love remains"); 
        coll.add("dog");
        //ergodic 
        //Each collection object has its own iterator 
        Iterator<String> it = coll.iterator(); 
        while(it.hasNext()){ 
            //Determine whether there are iterative elements
            String s = it.next();
            //Get the iterated element system out. println(s);
        }
    }
}
  1. If you continue to use the next method of the iterator when getting the collection elements, you will throw a Java util. NoSuchElementException has no collection element exception.

  2. During collection element acquisition, if you add or remove elements in the collection, you will not be able to continue the iteration, and a concurrent modificationexception will be thrown

2.2 implementation principle of iterator

When traversing the collection, first obtain the iterator object by calling the iterator() method of the collection, and then use the hashNext() method to judge whether there is the next element in the collection. If so, call the next() method to take out the element. Otherwise, it indicates that the end of the collection has been reached, and stop traversing the element.

When Iterator iterator object traverses the collection, it internally uses pointer to track the elements in the collection. Before calling the next method of the Iterator, the Iterator's index is located before the first element and does not point to any element. After calling the next method of the Iterator for the first time, the Iterator's index will move back one bit, point to the first element and return the element. When calling the next method again, the Iterator's index will point to the second element and return the element, And so on, until the hasNext method returns false, indicating that the end of the collection is reached and the traversal of the element is terminated.

2.3 precautions for using Iterator iterator [key points]

The program threw the concurrency modification exception of the iterator

In the process of traversing the collection with the iterator, if the length of the collection is modified (add or delete elements), the iterator will throw a concurrent modification exception

resolvent:

The first solution is to traverse the set without modifying the set length (that is, without adding or modifying elements)

The second solution:

There is a method called remove in the Iterator interface, which is also used to delete elements in the collection

void remove() deletes the elements in the collection retrieved using the next method

public class Demo01Iterator {
    public static void main(String[] args) {
        //Create a collection object and add elements to the collection
        ArrayList<String> list = new ArrayList<>();
        list.add("aaa");
        list.add("bbb");
        list.add("ccc");
        list.add("ddd");
        list.add("eee");
        //Iterate through the list collection using an iterator
        Iterator<String> it = list.iterator();
        while (it.hasNext()){
            String s = it.next();
            System.out.println(s);

            /*
                Requirement: add a judgment if the extracted element s is "ccc"
                Delete the element "ccc" in the collection
             */
            if("ccc".equals(s)){
                it.remove();//Using the iterator to delete the elements in the collection, delete it The element extracted by the next method
            }
        }
        System.out.println(list);
    }
}

The third solution: (it can only be used for the set under List)

The Iterator interface has a sub interface called ListIterator interface, which defines the method of adding elements to the collection

​ public interface ListIterator extends Iterator

Void add (E) inserts the specified element into the list (optional). ListIterator interface specific methods

void remove() deletes the elements in the collection retrieved using the next method

public class Demo01Iterator {
    public static void main(String[] args) {
        //Create a collection object and add elements to the collection
        ArrayList<String> list = new ArrayList<>();
        list.add("aaa");
        list.add("bbb");
        list.add("ccc");
        list.add("ddd");
        list.add("eee");
        //Use the listiterator method in the List interface to obtain the implementation class object of the listiterator iterator interface
        ListIterator<String> lit = list.listIterator();
        //Use the method hasNext in the ListIterator iterator to determine whether there are still elements in the collection
        while (lit.hasNext()){
            //Use the method next in the ListIterator iterator to fetch the elements in the collection
            String s = lit.next();
            System.out.println(s);

            /*
                Requirement: add a judgment if the extracted element s is "ccc"
                Add a new element "itcast" to the collection
             */
            if("ccc".equals(s)){
                lit.add("itcast");//Use the add method in the iterator to add elements to the collection
            }
        }
        System.out.println(list);
    }
}

The implementation class of the iterator is the inner class of each collection (interview – extension)

2.4 enhance for [ key ]

be careful:

The bottom layer of the enhanced for loop is an iterator, so when using the enhanced for loop traversal, the length of the collection cannot be modified, otherwise a concurrent modification exception will be thrown

public classs Demo(){
    Collection<String> coll = new ArrayList<>();
        coll.add("army officer's hat ornaments");
        coll.add("Xi Shi");
        coll.add("favorite concubine of emperor Minghuang");
        coll.add("Wang Zhaojun");
        for(String s : coll){
            System.out.println(s);
        }
	}
}

The enhanced for loop must have a traversed target, which can only be a Collection or an array;

Summary: Collection is the root interface of all single column collections. If you want to traverse a single column Collection, the general traversal method is iterator traversal or enhanced for traversal.

3, Generics

A generic is an unknown data type

A generic in Java is a pseudo generic: in There are generics in the java file There is no generic concept in the class file (reflection = = > generic erasure)

3.1 generic overview

[external chain picture transfer failed. The source station may have anti-theft chain mechanism. It is recommended to save the picture and upload it directly

3.2 benefits of using generics
  • What type is a generic type and what type is the element taken out. Without downward transformation, you can use element specific methods to avoid the trouble of type forced conversion.
  • When the ClassCastException of the runtime is transferred to the compilation time, it becomes a compilation failure.
3.3 definition and use of generics

Define and use classes that contain generics

/**
	When to use generics: when you are not sure what data type to use, it is an unknown data type
	Format:
    	public class Class name < define generic >{
     	   Where data types are used in a class, generics defined on the class can be used
    	}
	The class with all generics uses the following format:
   		When you create an object, you can assign a value to the generic type. The generic type depends on the value assigned
    	No assignment, default Object type
*/

public class Main{
    public static void main(String[] args){
        Person<Integer> p = new Person<>();
    }
    
    // Inner class
    public class Person<E> {
    	private E name;
    
    	public C getName() {
    	    return name;
    	}

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

Methods with generics [key]

/*
    Defining and using methods with generics (emphasis)
    Definition format: generics are defined between modifiers and return value types
        Modifier < define generics > return value type [use generics] method name (parameter list [use generics]){
            Method body;
        }
    When to determine the type of a generic type:
        When calling a method, the generic type in the method is what type of data is passed (reference data type)
 */
public class Main{
    public static void main(String[] args){
		Person p = new Person();
        
        p.show1("aaa"); // Generic E=String
        
        Person.show2("aaa"); // Generic S=String
        
        Integer in = Person.show3(12); // Generic V=Integer
    }
    
    // Inner class
    public class Person {
    	// Define a method that contains generics
        public <E> void show1(E e){
            System.out.print(e)
        }
         //Define a static method with generics
    	public static <S> void show02(S s){
        	System.out.println(s);
    	}
        
        //Define a static method with a generic type and a return value
    	public static <V> V show03(V v){
        	return v;
    	}
	} 
}

Interface with generics

/*
    Define an interface that contains generics
 */
public interface MyInter<I> {
    //The generics on the interface can be used wherever data is used in the interface
    public abstract void show(I i);
}
------------------------------------------------------------------------------
/**
	The first way to use an interface with generics:
		While the implementation class implements the interface, it specifies the data type of the interface generic
        Specify the type of generics and all generics in the interface
    Format:
        public class MyInterImpl1 implements MyInter<String>{
            public void show(String s) {}
        }
*/
public class MyInterImpl1 implements MyInter<Integer>{
    @Override
    public void show(Integer in){
        System.out.println(in);
    }
}
------------------------------------------------------------------------------
/**
    The second way to use interfaces with generics:
        When implementing a class to implement an interface, the implementation class will use whatever generic type the interface uses, and follow the interface
        It is equivalent to defining a class containing generics and determining the data type of generics when creating objects
 */
public class MyInterImpl2<I> implements MyInter<I>{
    @Override
    public void show(I i) {
        System.out.println(i);
    }
}
public static void Main(String[] args){
    MyInterImpl2<String> my01 = new MyInterImpl2<>();
    my01.show("aaa");
}
3.4 generic wildcards

Basic use of wildcards

When a generic class or interface is used, the generic type in the passed data is uncertain. You can use the wildcard <? > express

Advanced use of wildcards -- restricted generics

Upper limit of generics:

Format: type name <? Extensions class > object name

Meaning: only this type and its subclasses can be accepted

Lower bound of generics:

Format: type name <? Super class > object name

Meaning: only this type and its parent type can be accepted

? Represents a generic wildcard. If you want to pair? The value range of generic wildcard is limited. You can use generic restriction

4, List interface

4.1 introduction to list interface

​ java. util. The List interface inherits from the Collection interface and is an important branch of a single column Collection. It is customary to call the objects that implement the List interface a List Collection. Duplicate elements are allowed in the List set. All elements are stored in a linear way. The specified elements in the set can be accessed by index in the program. In addition, a feature of the List set is that the elements are orderly, that is, the storage order of the elements is consistent with the extraction order.

After reading the API, let's summarize:

List interface features:

  1. It is an ordered collection of elements. For example, the order of storing elements is 11, 22, 33. Then, the storage of elements in the set is completed in the order of 11, 22 and 33).

  2. It is a collection with an index. Through the index, you can accurately operate the elements in the collection (the same reason as the index of an array).

  3. There can be duplicate elements in the collection. Use the equals method of the element to compare whether it is a duplicate element.

4.2 common methods in list interface [ key points ]

As a sub interface of the Collection, List not only inherits all the methods in the Collection interface, but also adds some special methods to operate the Collection according to the element index, as follows:

  • public void add(int index, E element): adds the specified element to the specified position in the collection.
  • public E get(int index): returns the element at the specified position in the collection.
  • public E remove(int index): removes the element at the specified position in the list and returns the removed element.
  • Replace the specified element in the set with the specified element in E (the public value of the element in the set is returned before the element in E is updated).
4.3 ArrayList set

​ java. util. The structure of the ArrayList collection data store is an array structure. The addition and deletion of elements are slow and the search is fast. Because the functions most used in daily development are querying data and traversing data, ArrayList is the most commonly used collection.

4.4 LinkedList set

​ java. util. The structure of LinkedList set data storage is linked list structure. A collection that facilitates the addition and deletion of elements. [two way linked list]

Vector set (interview - extension)

java.util.Vector set implements List interface (List interface implemented after jdk1.2)

The Vector set is jdk1 A single column collection that exists during 0,

The earliest Collection, the Collection (ArrayList,LinkedList...) under the Collection interface, is jdk1 After 2

The Vector class can implement a growing array of objects. The Vector set is the same as the ArrayList set, and is also an array structure: fast query and slow addition and deletion. Unlike the implementation of the new collection, the Vector is synchronized.

**Synchronization technology: it can ensure the safety of multithreading, but it will reduce the efficiency of storing data in the collection, * * so the Vector is replaced by the more efficient ArrayList collection

--------------------------------------------------

Vector collection has some unique methods in 1.0: (used when learning Java Web)

void addElement(E obj) adds an element to the collection

Enumeration elements() returns an enumeration of the components of this vector.

Enumeration interface: vector enumeration, jdk1 Iterator for period 0

boolean hasMoreElements() determines whether there are any elements in the collection = = > the hasNext method in the iterator

E nexterelement() retrieves the element in the collection = = > the next method in the iterator

5, Collections collection utility class

​ java.utils.Collections is a collection tool class used to operate on collections.

5.1 common functions of collections
  • Common methods are as follows:
  • Public static void shuffle (list <? > list): disorganize the collection order.
  • Public static void sort (list): sort the elements in the collection according to the default rules.
  • Public static void sort (list, comparator <? Super T >): sort the elements in the collection according to the specified rules.
5.2 Comparator (Comparable)
public class Main() {
    public static void main(String[] args){
        // Create an ArrayList collection object 
        ArrayList<Integer> list01 = new ArrayList<>(); 
		Collections.addAll(list01, 1, 3, 2, 4);
        System.out.println(list01);//[1, 3, 2, 4]
        
        // Use the method sort in the Collections collection tool class to sort the elements in the collection according to the rules generated by the comparator 
        Collections.sort(list01, new Comparator<Integer>() { 
            @Override 
            public int compare(Integer o1, Integer o2) { 
                //Descending order: 
                o2-o1 return o2-o1; 
            } 
        }); 
        System.out.println(list01);//[4, 3, 2, 1]
        
        // Use the method sort in the Collections collection tool class to sort the elements in the collection according to the rules generated by the comparator 
        Collections.sort(list01, new Comparator<Integer>() { 
            @Override 
            public int compare(Integer o1, Integer o2) { 
                //Ascending order: 
                o1-o2 return o1-o2; 
            }
        }); 
        System.out.println(list01);//[1, 2, 3, 4]
    }
}

If an object of a custom class is stored in the collection, the custom class needs to implement the Comparable interface

/* Custom Student class */
package com.itheima.task01;

public class Student implements Comparable<Student>  {
    private String name;
    private int age;
	
    // Nonparametric and full parameter construction methods
	// Setters / getters method
    // toString method

    @Override
    public int compareTo(Student o) {
        // Ascending order
        return this.getAge()-o.getAge();
    }
}

/* Test class */
public void Main(){
    public static void main(String[] args){
        // Create an ArrayList collection object, and generically use Student
        ArrayList<Student> Students = new ArrayList<>();
        Students.add(new Student("Zhang San", 18));
        Students.add(new Student("Li Si", 20));
        Students.add(new Student("Wang Wu", 19));
        Students.add(new Student("Zhao Liu", 18));
        Students.add(new Student("pseudo-ginseng", 21));

        Collections.sort(Students);
        System.out.println(Students);
    }
}
5.3 variable parameters [ key ]

It's jdk1 New features after 5
effect:
[used as a parameter of the method, you can receive any parameter of the same data type]
When we define a method, the data type of method parameters has been determined, but the number of parameters is uncertain, we can use variable parameters
Format:
Modifier return value type method name (data type... Variable name){
Method body;
​ }
Data type... Variable name: variable parameter
Int... a: can receive any integer of type int (pass 1 parameter, pass 10 parameters... Pass 100 parameters...)
String... a: you can receive any integer of string type (without passing parameters, pass 1 parameter, pass 10 parameters... Pass 100 parameters...)

Important: remember that variable parameters can receive any number of elements of the same data type

be careful:

  • The bottom layer of variable parameters is an array, which defines arrays of different lengths to store different numbers passed
  • The parameter list of a method can only have one variable parameter
  • The parameter list of a method has multiple parameters, and the variable parameters must be written in the last side

6, Set interface

6.1 introduction to HashSet set

java.util.HashSet implements Set interface
This class implements the Set interface and is supported by a hash table (actually a HashMap instance).
It does not guarantee the iterative order of set; In particular, it does not guarantee that the order is constant.
HashSet set features:
1. Duplicate elements are not allowed to be stored
2. Methods with indexes are not included
3. It is an unordered collection, and the order of stored elements and extracted elements [May] be inconsistent
4. The bottom layer is a hash table structure
JDK1. Before 8: array + one-way linked list
JDK1. After 8: array + one-way linked list | array + red black tree

6.2 structure of data stored in HashSet set (hash table)

At jdk1 Before 8, the bottom layer of hash table was implemented by array + linked list, that is, array was used to deal with conflicts, and linked lists with the same hash value were stored in an array. However, when there are many elements in a bucket, that is, there are many elements with equal hash values, the efficiency of searching by key value in turn is low.

And jdk1 In 8, the hash table storage is realized by array + linked list + red black tree. When the length of the linked list exceeds the threshold (8), the linked list is converted into a red black tree, which greatly reduces the search time

[external chain picture transfer failed. The source station may have anti-theft chain mechanism. It is recommended to save the picture and upload it directly

The principle of using HashSet set to store strings without repetition (expand the knowledge point understanding)

[external chain picture transfer failed. The source station may have anti-theft chain mechanism. It is recommended to save the picture and upload it directly

6.3 HashSet stores custom type elements [ key ]

When storing custom type elements in the HashSet, you need to override the hashCode and equals methods in the object and establish your own comparison method to ensure the uniqueness of the objects in the HashSet set

6.4 LinkedHashSet

java. util. Linkedhashset extensions
Hash table and link list implementation of Set interface with predictable iteration order.
The difference between this implementation and HashSet is that the latter maintains a double linked list running on all items.
LinkedHashSet set features:
1. Duplicate elements are not allowed to be stored
2. Methods with indexes are not included
3. It is an ordered collection, and the stored elements are in the same order as the extracted elements
4. The bottom layer is a hash table structure + one-way linked list
JDK1. Before 8: array + one-way linked list + one-way linked list
JDK1. After 8: array + one-way linked list + one-way linked list | array + red black tree + one-way linked list

7, Map collection

7.1 general

java. util. Map < K, V > interface key: Value: value
characteristic:
1. The map set is a double column set. Each element contains two values, one key and one value
2. The key in the map set cannot be repeated, but the value can be repeated
3. A key in the map set can only correspond to one value
4. The data types of key and value in the map set can be the same or different

7.2 common subclasses of map

1.java. util. HashMap < K, V > set implements map < K, V > interface
Implementation of Map interface based on hash table. This class does not guarantee the order of the mapping, especially it does not guarantee that the order is constant.
a. The bottom layer of the HashMap set is a hash table, and the structure is the same as that of the HashSet
b. Is an unordered collection: the order of storing elements and fetching elements may be inconsistent
2.java. util. LinkedHashMap < K, V > set extends HashMap < K, V > Set
The hash table and link list implementation of the Map interface has a predictable iterative order.
This implementation differs from HashMap in that it maintains a double linked list that runs on all items.
a. The bottom layer of the LinkedHashMap set is hash table + one-way linked list, and the data structure is the same as that of the LinkedHashMap set
b. Is an ordered set

7.3 common methods of map
  • public V put(K key, V value): adds the specified key and value to the Map collection.
  • public V remove(Object key): deletes the key value pair element corresponding to the specified key in the Map collection, and returns the value of the deleted element.
  • public V get(Object key) gets the corresponding value in the Map collection according to the specified key.
  • public Set keySet(): get all the keys in the Map Set and store them in the Set.
  • public Set<Map. Entry < K, V > > entryset(): get the set of all key value pair objects in the map set (set set).
  • public boolean containKey(Object key): judge whether this key exists in the collection.

When using the put method, if the specified key does not exist in the set, there is no value corresponding to the key, null is returned, and the specified key value is added to the set;

If the specified key exists in the set, the return value is the value corresponding to the key in the set (the value is the value before replacement), and the value corresponding to the specified key is replaced with the specified new value.

7.4 traversal of map

Method 1: key value finding method

[external chain picture transfer failed. The source station may have anti-theft chain mechanism. It is recommended to save the picture and upload it directly

public class Main() {
    public static void main(String[] args) {
        Map<String,Integer> map = new HashMap<>();
        map.put("Delireba",168);
        map.put("Gulinaza",165);
        map.put("Feng Timo",150);
        map.put("Lin Zhiling",180);
        
        for (String key : map.keySet()) {
            System.out.println(key + "==>" + map.get(key));
        }
    }
}

Method 2: key value pair method

[the external chain image transfer fails. The source station may have an anti-theft chain mechanism. It is recommended to save the image and upload it directly (img-f7bX7UvE-1627644868798)(images/image18.png)]

public class Main() {
    public static void main(String[] args) {
        Map<String,Integer> map = new HashMap<>();
        map.put("Delireba",168);
        map.put("Gulinaza",165);
        map.put("Feng Timo",150);
        map.put("Lin Zhiling",180);
        
        for (Map.Entry<String, Integer> entry : map.entrySet()) {
            System.out.println(entry.getKey() + "==>" + entry.getValue());
        }
    }
}
7.5 HashMap storage custom types
/* Student class */
public class Student { 
    private String name; 
    private int age; 
    
    //Construction method 
    //get/set 
    @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); 
    } 
}

When storing a custom object in a HashMap, if the custom object exists as a key, to ensure that the object is unique, you must copy the hashCode and equals methods of the object (if you forget, please review the HashSet to store the custom object).

7.6 LinkedHashMap introduction

java. util. LinkedHashMap < K, V > set extends HashMap < K, V > Set
The hash table and link list implementation of the Map interface has a predictable iterative order.
This implementation differs from HashMap in that it maintains a double linked list that runs on all items.
a. The bottom layer of the LinkedHashMap set is hash table + one-way linked list, and the data structure is the same as that of the LinkedHashMap set
b. Is an ordered set

7.7 Hashtable set [ interview ]

​ java. util. Hashtable < K, V > set implements map < K, V > interface (implemented after jdk1.2)
This class implements a hash table that maps keys to corresponding values. Any non null object can be used as a key or value.

Features of HashMap collection:
1. The bottom layer of HashMap set is a hash table structure
2. The HashMap set is jdk1 After version 2
3.HashMap collection allows null keys and null values to be stored
4. The HashMap collection is out of sync and efficient (multithreading is unsafe)

Features of Hashtable set:
1. The bottom layer of the hashtable set is a hash table structure
2. The hashtable set is jdk1 A two column set that existed in version 0 (the earliest two column set)
3.Hashtable collection is not allowed to store null keys and null values
4.Hashtable collection is synchronous and inefficient (multi thread safety)

The collection efficiency of Hashtable is not as high as that of HashMap, so it has been eliminated
However, the Properties collection, a subclass of the Hashtable collection, is still active on the stage of history

Properties collection: the only collection related to the flow

Keywords: JavaSE set HashMap arraylist map

Added by sethcox on Mon, 03 Jan 2022 03:51:41 +0200