This is the 28th day of my participation in the August Text Challenge.More challenges in August

Java collection

preface

  • 8.27
  • Don’t stop my music and programming learning
  • Java is the first serious system learning language, we must learn it systematically and comprehensively!
  • Ollie here!!
  • Nothing can stop it

The target

  1. What is a set
  2. Application scenarios of collections
  3. Contrast Java arrays with collections
  4. The architecture of Java collections
  5. Combined with examples to explain the practical application of sets

1. What is a set

In computer science, a collection is a combination of a variable number of data items (perhaps zero) that may share certain characteristics and need to be operated together in a certain manner.

Collections in Java are mainly divided into java.util.Collection and java.util.Map interfaces.

Java collections framework:

Tips: ArrayList, LinkedList, HashSet, and HashMap at the bottom of the diagram are common implementation classes

1.1 the Collection

The implementation of the java.util.Collection interface can be used to store Java objects. For example, all the players in the NBA can be considered a Collection.

Collection can be divided into three sub-interfaces:

  1. List: sequence must be followedSave elements sequentially, so it is ordered and allows repetition;
  2. Queue: queue, according toQueuing rules to determine the order in which objects are generated, orderly, allowing repetition;
  3. Set: set, cannot be repeated.

1.2 the Map

The implementation of the java.util.map interface can be used to represent mappings between key and value objects. A map represents a set of key objects, each of which maps to a value object. So you can look up values by keys.

Such as:

Each player in the NBA has his or her own player number, which can be represented by Map.

2. Application scenarios of collections

2.1 Arrays and Sets

Before introducing collections, let’s take a look at arrays versus collections.

We know that arrays and collections are used to store a group of data, but the capacity of arrays is fixed, while the capacity of collections is dynamically variable.

As for the data types that can be stored, arrays can hold both basic and reference data types, while collections can only hold reference data types. Basic data types need to be converted to the corresponding wrapper classes before they can be stored in collections.

2.2 Collection Application Scenarios

  • It is impossible to predict how much data will be stored: since array sizes are fixed, it is more appropriate to use collections to store a dynamic amount of data;

  • At the same time, store one-to-one data. For example, store NBA player numbers. To facilitate retrieval of NBA player numbers, you can use Map to associate the UID of NBA players with the corresponding numbers.

  • Data deduplication: the use of arrays to achieve traversal, low efficiency, and the Set itself has the characteristics of cannot be repeated;

  • Adding and deleting data: Adding and deleting an array requires traversing and moving elements in the array. If the operation is frequent, the efficiency will decrease.

3. The List collection

3.1 Concepts and Features

A List is a collection of ordered elements that can be repeated, called a sequence. Sequences can precisely control where each element is inserted or where elements are deleted. List is a subinterface of Collection. It has two main implementation classes, ArrayList and LinkedList.

3.2 ArrayList implementation classes

An ArrayList can be understood as a dynamic array, and its capacity can grow dynamically. If the capacity of an element is used up, the element is automatically expanded to 1.5 times its original size.

3.2.1 Construction method

  • ArrayList()Construct an empty list with an initial capacity of 10;
  • ArrayList(int initialCapacity): Constructs an empty list of specified capacities;
  • ArrayList(Collection<? extends E> c): Constructs a list of the specified collection elements in order returned by the collection iterator.

In code, we can instantiate an ArrayList object like this:

// Construct instantiation with no arguments and initial capacity of 10
List arrayList1 = new ArrayList();
Instantiate an empty list with an initial capacity of 20
List arrayList2 = new ArrayList(20);
// Instantiate a list whose collection elements are arrayList2 (since arrayList2 is an empty list, the instantiated object is also an empty list)
List arrayList3 = new ArrayList(arrayList2);
Copy the code

3.2.2 Common member methods

  • void add(E e): appends the specified element to the end of the list;
  • void add(int index, E element): inserts the specified element at the specified position in this list;
  • E remove(int index): Deletes the element at the specified position in this list.
  • boolean remove(Object o): Deletes the first occurrence of the element from the list if the specified element exists;
  • void clear(): Removes all elements from this list;
  • E set(int index, E element): Replaces the element at the specified position in this list with the specified element;
  • E get(int index): returns the element at the specified position in this list;
  • boolean contains(Object o): Returns true if the list contains the specified element, false otherwise;
  • int size(): Returns the number of elements in the list;
  • Object[] toArray(): Returns an array containing all the elements in this list in the correct order (from the first element to the last).

3.3 instance

3.3.1 Added elements

package com.caq.oop.demo08;

import java.util.ArrayList;

public class Test {
    public static void main(String[] args) {
        // instantiate an empty list
        ArrayList arrayList = new ArrayList();
        for (int i = 0; i < 5; i++) {
            // Appends element I to the end of the list
            arrayList.add(i);
            // Prints the listSystem.out.println(arrayList); }}}Copy the code

Running results:

[0, 1] [0, 1, 2] [0, 1, 2, 3] [0, 1, 2, 3]Copy the code

The code first instantiates an ArrayList object, and then loops through it five times using a for loop, appending variable I to the ArrayList object each time and printing the contents of the list. The result clearly shows the process of adding elements each time.

Tips: Because ArrayList’s parent, AbstractCollection, overrides the toString() method, you can visually display the elements in the list by printing the list directly.

3.3.2 Introduction to generics

Tips: Genericity

Introduce generics and how to use them.

If you useIDEAWhen you write the code above, there will be three yellow warnings as shown below:

sinceIDEUnchecked: + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +IDEtheThe generic inspection, clickableTry to generify 'ArrayListDemo1.java'Button:

One will appearGenerifyPopover, click directlyRefactorButton:

The code now looks like the following, with the three warnings successfully removed:

List types much more behind a pair of brackets “< >” < > it is a Java package type Integer, behind the ArrayList type too much are a pair of brackets, it hosted in < > is a Java generic type parameters, It represents an arrayList object used to hold data of type Integer.

We just need to know that doing so will remove the IDEA warning. More on that later!

Since the List already specifies a generic parameter type of Integer, the following ArrayList does not need to be specified again. Of course you could write this (but you don’t have to) :

List<Integer> arrayList = new ArrayList<Integer>();
Copy the code

Similarly, if you want to store elements of type String into an arrayList, just change

to

. Let’s look at another example:

Examples demonstrate

package com.caq.oop.demo08;

import java.util.ArrayList;
import java.util.List;

public class Test {

    public static void main(String[] args) {
        // instantiate an empty list
        List<String> arrayList = new ArrayList<>();
        // Prints Hello to the end of the arrayList list
        arrayList.add("Hello");
        arrayList.add("Hello");
        // Prints the list
        System.out.println(arrayList);
        // Insert the string element Monkey into the list at index 1
        arrayList.add(1."Monkey"); }}Copy the code

Two forms, directly add the last character to change or specify the index to add, IDEA this point is still very good!!

[Hello, Hello]
[Hello, Monkey, Hello]
Copy the code

We instantiate an ArrayList object, call add(E E) twice, and insert Hello and World elements into the end of the list. The element is [Hello, World], then call Add (int index, E Element). Inserts the string element Java into this list at index 1, so the element in the list is [Hello, Java, World].

3.3.3 Deleting elements

Examples demonstrate

package com.caq.oop.demo08;

import java.util.ArrayList;
import java.util.List;

public class Test {

    public static void main(String[] args) {
        // instantiate an empty list
        List<String> arrayList = new ArrayList<>();
        // Prints Hello to the end of the arrayList list
        arrayList.add("Hello");
        arrayList.add("Hello");
        arrayList.add("Hello");
        arrayList.add("Tiger");
        // Prints the list
        System.out.println(arrayList);
        // Drop the element with index 3
        arrayList.remove(3);
        // Prints the list
        System.out.println(arrayList);

        // Remove the first occurrence of the Hello element in the list
        arrayList.remove("Hello"); System.out.println(arrayList); }}Copy the code

Running results:

[Hello, Hello, Hello, Tiger]
[Hello, Hello, Hello]
[Hello, Hello]
Copy the code

We add four string elements to the list of [Hello, World, Hello, Java], and then call remove(int index) to remove the element at index 3. At this time, the list content is [Hello, World, Hello], again call remove(Object O) method, delete the first occurrence of Hello element in the list, now the list content is [World, Hello].

Ori to !!!!

3.3.4 Modifying elements

You can use the set() method to modify elements in a list as shown in the following example:

Examples demonstrate

package com.caq.oop.demo08;

import java.util.ArrayList;
import java.util.List;

public class Test {

    public static void main(String[] args) {
        // instantiate an empty list
        List<String> arrayList = new ArrayList<>();
        arrayList.add("Hello!");
        arrayList.add("Hello!");
        / / print
        System.out.println(arrayList);
        // Replace the element at index position 1 with the string element Hello
        arrayList.set(1."Monkey"); System.out.println(arrayList); }}Copy the code

Running results:

[Hello!, Hello!]  [Hello!, Monkey]Copy the code

3.3.5 Querying Elements

We can use the get() method to get elements from a list as shown in the following example:

Examples demonstrate

package com.caq.oop.demo08;

import java.util.ArrayList;
import java.util.List;

public class Test {

    public static void main(String[] args) {
        // instantiate an empty list
        List<String> arrayList = new ArrayList<>();
        arrayList.add("Hello0");
        arrayList.add("Hello1");
        // Use get to query the element with index 1
        for (int i = 0; i < arrayList.size(); i++) {
            System.out.println("Index as" + i + "Elements are:"+ arrayList.get(i)); }}}Copy the code

Running results:

The index for0The element is: Hello0 index is1The element is Hello1Copy the code

When we use the for loop to iterate over the list, let the qualification be I < arrayList.size(); The size() method gets the number of elements in the list.

3.2.7 Common Operations of user-defined Classes

Please check the following example:

Examples demonstrate

package com.caq.oop.demo08;
/* When we print a reference to an Object, the toString() method of that Object is actually called by default. When the printed Object does not override the toString() method of Object, the toString() method of Object is called by default. When we print that the object's class overrides toString(), we call the overridden toString() method. Overrides usually return the attributes of the class object. The toString method is called automatically at println. Converting an Object to a string is called serialization. ToString is a method provided by the Object class, and our Person class inherits from The Object class by default. We can override toString to implement our own version of the converting string method */

// Custom classes need to override the toString method to display objects as strings
import java.util.ArrayList;
import java.util.List;

public class Test {
    static class NBA {
        private String name;

        private String position;
        
        public NBA(String name, String position) {
            this.name = name;
            this.position = position;
        }

        public String getName(a) {
            return name;
        }

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

        public String getPosition(a) {
            return position;
        }

        public void setPosition(String position) {
            this.position = position;
        }

        @Override
        public String toString(a) {
            return "NBA{" +
                    "name='" + name + '\' ' +
                    ", position='" + position + '\' ' +
                    '} ';
        }

        public static void main(String[] args) {
            // instantiate an empty list
            List<NBA> arrayList = new ArrayList<>();
            // Instantiate three NBA objects
            NBA nba1 = new NBA("Jordan"."Shooting guard SG.");
            NBA nba2 = new NBA("James"."Small forward SF");
            NBA nba3 = new NBA("Arsenal"."Point guard PG");

            // Add a new element
            arrayList.add(nba1);
            arrayList.add(nba2);
            arrayList.add(nba3);
            System.out.println(arrayList);

            // Delete elements
            arrayList.remove(nba3);
            System.out.println("Delete dynamic array arrayList is:"+arrayList);
            arrayList.remove(1);
            System.out.println("Arraylist of deleted elements with index 1 is:"+arrayList);

            // Modify the element
            NBA nba4 = new NBA("Griffin"."Power forward PF");
            arrayList.set(0,nba4);
            // Query element to force the class object obtained by get () to type NBA
            NBA player = arrayList.get(0);
            System.out.println("Nicknames for players with index 0 are:"+player.getName());
            System.out.println("The position of a player with index 0 is:"+player.getPosition()); }}}Copy the code

Running results:

[NBA{name='Jordan', position='Shooting guard SG'}, NBA{name='James', position='Small Forward SF'}, NBA{name='库里', position='Point Guard PG'}] delete dynamic array arrayList: [NBA{name='Jordan', position='Shooting guard SG'}, NBA{name='James', position='Small Forward SF'}] delete the dynamic array index is1The element arrayList is: [NBA{name='Jordan', position='Shooting guard SG'}] index0The player nicknames are: Griffin index for0Player position: PF power forwardCopy the code

For demonstration purposes, we define a static inner class NBA that has two properties name and Position, defines the getter and setter for the property, and overwrites the toString() method. In the main() method, we implement adding, deleting, and checking custom classes in the ArrayList.

3.4 LinkedList implementation class

LinkedList is a List implemented as a two-way LinkedList. Like ArrayList, it is sorted by index position, but its elements are joined in both directions, so sequential access is very efficient and random access is less efficient.

3.4.1 Construction method

  • LinkedList(): Constructs an empty list;
  • LinkedList(Collection<? extends E> c): Constructs a list of the specified collection elements in order returned by the collection iterator.

3.4.2 Common Member methods

  • void add(E e): appends the specified element to the end of the list;
  • void add(int index, E element): inserts the specified element at the specified position in this list;
  • void addFirst(E e): inserts the specified element at the beginning of the list;
  • vod addLast(E e): adds the specified element to the end of the list;
  • E remove(int index): Deletes the element at the specified position in this list.
  • boolean remove(Object o): Deletes the first occurrence of the element from the list if the specified element exists;
  • void clear(): Removes all elements from this list;
  • E set(int index, E element): Replaces the element at the specified position in this list with the specified element;
  • E get(int index): returns the element at the specified position in this list;
  • E getFirst(): returns the first element of this list;
  • E getLast(): returns the last element of the list;
  • boolean contains(Object o): Returns true if the list contains the specified element, false otherwise;
  • int size(): Returns the number of elements in the list;
  • Object[] toArray(): Returns an array containing all the elements in this list in the correct order (from the first element to the last).

4. Set the Set

4.1 Concepts and Features

A Set is a Set whose elements are unordered and cannot be repeated. We call it a Set (an order can be repeated as a sequence). Set is a subinterface of Collection. Its main implementation classes include: HashSet, TreeSet, LinkedHashSet, EnumSet, etc. The most commonly used implementation classes of HashSet will be introduced in detail below.

4.2 HashSet implementation class

The HashSet class relies on a hash table (which is actually a HashMap instance, described below). Elements in a HashSet are unordered and hashed.

4.2.1 Construction method

  • HashSet()Construct a new empty set; The default initial capacity is 16 (most commonly used) and the load factor is 0.75.
  • HashSet(int initialCapacity)Construct a new empty set; Has a specified initial capacity, load factor of 0.75;
  • HashSet(int initialCapacity, float loadFactor)Construct a new empty set; Supported HashMap instances have specified initial capacity and specified load factor;
  • HashSet(Collection<? extends E> c): Constructs a new collection containing elements from the specified collection.

4.2.2 Common member methods

The common member methods for a HashSet are as follows:

  • boolean add(E e): Adds the specified element to the collection if it does not already exist;
  • boolean contains(Object o): Returns true if this collection contains the specified element, false otherwise;
  • boolean isEmpty(): Returns true if this collection contains no elements, false otherwise;
  • Iterator<E> iterator(): returns an iterator for the elements in this collection;
  • boolean remove(Object o): Removes the specified element (if present) from the collection;
  • int size(): Returns the number of elements in this collection.

4.3 instance

4.3.1 New elements

Examples demonstrate

package com.caq.oop.demo08;

import java.util.Set;
import java.util.HashSet;

public class Test {
    public static void main(String[] args) {
        // instantiate a new empty set
        Set<String> hashSet = new HashSet<>();
        // Add elements in turn to the hashSet
        hashSet.add("Monkey");
        hashSet.add("Monkey");
        hashSet.add("Tiger");
        hashSet.add("Dog");
        hashSet.add("Cat");
        // Prints the contents of the hashSet
        System.out.println("The contents of the hashSet are:"+ hashSet); }}Copy the code

Running results:

The contents of the hashSet are: [Monkey, Cat, Dog, Tiger]Copy the code

In our example, we added Monkey elements to the hashSet twice, and due to the non-repeatable nature of elements in the set, only one Monkey element is allowed in the set. We also observe that the order in which the elements are printed is different from the order in which we add them, which validates the unordered nature of the set.

Tips: Since HashSet’s parent, AbstractCollection, overrides the toString() method, printing the set directly makes it possible to visually display the elements in the set.

4.3.2 Deleting Elements

Set elements can be removed using the remove() method

Examples demonstrate

package com.caq.oop.demo08;

import java.util.ArrayList;
import java.util.Set;
import java.util.HashSet;

public class Test {
    public static void main(String[] args) {
        // instantiate a new empty set
        Set<String> hashSet = new HashSet<>();
        // Add elements in turn to the hashSet
        hashSet.add("Monkey");
        hashSet.add("Monkey");
        hashSet.add("Tiger");
        hashSet.add("Dog");
        hashSet.add("Cat");
        System.out.println("The contents of the hashSet are:" + hashSet);

        hashSet.remove("Cat");
        System.out.println("The contents of the hashSet are:"+ hashSet); }}Copy the code

Running results:

[Monkey, Cat, Dog, Tiger] [Monkey, Dog, Tiger]Copy the code

4.3.3 Querying elements

We know that ArrayList uses a GET method to query elements, but HashSet does not provide a similar GET method to query elements.

Here we introduce an Iterator interface. All collections implement the Iterator interface, which iterates through various Collection elements in a uniform way. Let’s look at some common methods for Iterator interfaces:

  • hasNaxt()Method to check if there is another element in the collection;
  • next()Method returns the next element in the collection;
  • iterator(): returns an iterator for the elements in this collection.

Examples are as follows:

Examples demonstrate

package com.caq.oop.demo08;

import java.util.Set;
import java.util.HashSet;
import java.util.Iterator;

public class Test {
    public static void main(String[] args) {
        // instantiate a new empty set
        Set<String> hashSet = new HashSet<>();
        // Add elements in turn to the hashSet
        hashSet.add("Monkey");
        hashSet.add("Tiger");
        hashSet.add("Dog");
        hashSet.add("Cat");
        System.out.println("The contents of the hashSet are:" + hashSet);

        // Get an iterator for the elements in the hashSet
        Iterator<String> iterator = hashSet.iterator();
        System.out.println("The iterator traversal result is:");
        while(iterator.hasNext()) { System.out.println(iterator.next()); }}}Copy the code

Running results:

The iterator [Monkey, Cat, Dog, Tiger] iterates to Monkey Cat Dog TigerCopy the code

4.3.4 Common Operations of user-defined Classes

Please check the following example:

Examples demonstrate

package com.caq.oop.demo08;

import java.util.Iterator;
import java.util.Set;
import java.util.HashSet;

public class Test {

   static class NBA{
       private String name;
       private String positon;

       public NBA(String name, String positon) {
           this.name = name;
           this.positon = positon;
       }

       public String getName(a) {
           return name;
       }

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

       public String getPositon(a) {
           return positon;
       }

       public void setPositon(String positon) {
           this.positon = positon;
       }

       @Override
       public String toString(a) {
           return "NBA{" +
                   "name='" + name + '\' ' +
                   ", positon='" + positon + '\' ' +
                   '} ';
       }

       public static void main(String[] args) {
           Set<NBA> hashSet = new HashSet<>();
           Instantiate three NBA objects
           NBA nba1 = new NBA("Kobe"."SG");
           NBA nba2 = new NBA("LBJ"."SF");
           NBA nba3 = new NBA("Pual"."PG");


           // Add a new element
           hashSet.add(nba1);
           hashSet.add(nba2);
           hashSet.add(nba3);

           // Use Iterator to iterate over a hashSet
           Iterator<NBA> iterator = hashSet.iterator();
           System.out.println("The iterator traversal result is:");
           while (iterator.hasNext()) {
               System.out.println(iterator.next());
           }

           // Find and delete
           if (hashSet.contains(nba1)){
               hashSet.remove(nba1);
           }
           System.out.println("After removing the object with name Kobe, the collection element is:"); System.out.println(hashSet); }}}Copy the code

Running results:

The iterator traversal results in NBA{name='Pual', positon='PG'}
NBA{name='LBJ', positon='SF'}
NBA{name='Kobe', positon='SG'} after removing the object with name as Kobe, the collection element is: [NBA{name='Pual', positon='PG'}, NBA{name='LBJ', positon='SF'}]
Copy the code

For demonstration purposes, we define a static inner class ImoocStudent that has two properties nickname and position, defines the getter and setter for the property, and overwrites the toString() method. In the main() method, we implement adding, deleting, modifying, and reviewing custom classes in a HashSet, using iterators to traverse elements.

5. Map collections

5.1 Concepts and Features

We already know that a Map is a mapping between objects in the form of key-value pairs, which exist as instances of objects of type java.util.map. Entry.

You can use keys to find values, and a map cannot contain duplicate keys, but values can be repeated. Each key can map to at most one value.

5.2 HashMap implementation classes

HashMap is one of the most commonly used implementation classes of the java.util.Map interface. The underlying implementation of HashSet is implemented through HashMap, which allows null keys and null values.

5.2.1 Construction method

  • HashMap(): Constructs a new empty map; The default initial capacity is 16 (most commonly used) and the load factor is 0.75.
  • HashMap(int initialCapacity): Constructs a new empty map; Has a specified initial capacity, load factor of 0.75;
  • HashMap(int initialCapacity, float loadFactor): Constructs a new empty map; To support theHashMapThe instance has a specified initial capacity and a specified load factor;
  • HashSet(Map<? extends K, ? extends V> m): Constructs a new mapping that contains the same as the specified mapping.

5.2.2 Common Member methods

  • void clear(): Deletes all mappings from the mapping.
  • Set<Map, Entry<K, V>> entrySet: Returns the collection of mappings contained in this mapping;
  • V get(Object key): Returns the value to which the specified key is mapped, or null if the mapping does not contain a key mapping;
  • Set<K> keySet: Returns what is contained in this mapkeyThe combination of;
  • V put(K key, V value): associates the specified value with the specified key in this mapping;
  • V remove(Object key): If it exists, the mapping for the specified key is removed from this mapping.
  • Collection<V> values: Returns the collection contained in this map.

5.3 instance

Let’s use HashMap to implement an Example of an English-Chinese dictionary.

Examples demonstrate

package com.caq.oop.demo08;

import java.util.HashMap;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Set;

public class Test {
    public static void main(String[] args) {
        Map<String, String> map = new HashMap<>();
        // Add data
        map.put("Monkey"."Monkey");
        map.put("Tiger"."Tiger");
        map.put("Rabbit"."Rabbit");

        / / print the map
        System.out.println(map);

        // Delete the data whose key is monkey
        map.remove("Monkey");
        System.out.println("After deleting the map with key Monkey, the map contents will be:");
        System.out.println(map);

        // Modify the element
        map.put("Tiger"."Mouse");
        System.out.println("After modifying the key to Tiger, Tiger=" + map.get("Tiger"));

        / / traverse map
        System.out.println("Obtain key-value mapping by iterating through entrySet method:");
        Set<Entry<String, String>> test = map.entrySet();
        for (Entry<String, String> entry : test) {
            System.out.println(entry.getKey() + "-" + entry.getValue());
        }

        // Find the value of Rabbit in the set
        Set<String> keySet = map.keySet();
        for (String key : keySet) {
            if (key.equals("Rabbit")) {
                System.out.println("The value of Rabbit is:" + map.get(key));
                break; }}}}Copy the code

Running results:

{Monkey= Monkey, Rabbit= Rabbit, Tiger= Tiger} {Rabbit= Rabbit, Tiger= Tiger} After setting the key to Tiger, Tiger= mouse iterates through the entrySet method to obtain the key-value mapping: Rabbit-rabbit Tiger-mouse The value of Rabbit is RabbitCopy the code

In this example, the Map key is a string and the Map value is a string. Note that when we create a HashMap, we have

at the end of the Map type, indicating that the key and value to be stored in the Map are of type String respectively. While iterating through the map, we call the entrySet method, which returns a collection of the mappings contained in the map. By finding a value by key, we can call the keySet method to get the set of keys in the map, and iterate over the set to find the corresponding key, and get the value by key.
,>

6. Summary

Java collections, defined in the java.util package. Collections in Java have two main interfaces: Collection and Map.

A List collection is a collection of ordered elements that can be repeated;

A Set is a Set whose elements are unordered and cannot be repeated;

A Map is a mapping between objects stored as key-value pairs that support generics.

We introduce the usage of common implementation classes for three interfaces respectively.

That’s the point. It takes a lot of coding practice.