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

An overview,

The Collection framework classes in Java can be divided into Collection and Map. The differences are as follows:

  1. A Collection is a single-column Collection. A Map is a collection of bicolumns

  2. The Set element is unique in the Collection; The Map must have unique keys and duplicate values

  3. The data structure of a Collection is element-specific; The Map data structure is key-specific

Ii. Collection System:

Collection consists of two systems, List and Set

List features:

  • A List represents an ordered, repeatable collection of elements, each of which has a corresponding sequential index.

  • List allows the use of duplicate elements, which can be indexed to access collection elements at a specified location.

  • List sets the index of elements by default in the order they are added.

  • The List collection has added methods to manipulate collection elements by index

Set features: access disorder, elements can not be repeated

Set the List:

ArrayList, LinkedList, Vector(obsolete)

The greatest purpose of collections is access; The List collection is characterized by orderly access. It can store repeated elements and operate elements with subscripts.

ArrayList:

The bottom layer is to use the array implementation, so the query speed is fast, add and delete speed is slow

 public static void main(String[] args) {
        // Use ArrayList to add and iterate
        List<String> list = new ArrayList<String>();

        list.add("a");
        list.add("b");
        list.add("c");

        // The first type of traversal uses iterators
        Iterator<String> it = list.iterator();
        while(it.hasNext()){
            String next = it.next();
            System.out.println(next);
        }
        System.out.println("-- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -");
        // The second traversal method, foreach
        for(String str : list){ System.out.println(str); }}Copy the code

LinkedList:

Is based on the linked list structure to achieve, so the query speed is slow, add and delete fast, provides a special method, at the end of the element operation (add and delete check).

Use LinkedList to implement stacks and queues; Stacks are fifo and queues are fifO

package org.example.test;

import java.util.LinkedList;

/** * use LinkedList to simulate the characteristics of stack */
public class Test12 {

    private LinkedList<String> linkList = new LinkedList<String>();

    / / pressure stack
    public void push(String str){
        linkList.addFirst(str);
    }

    / / out of the stack
    public String pop(a){
        return linkList.removeFirst();
    }

    / / check
    public String peek(a){
        return linkList.peek();
    }

    // Check whether it is null
    public boolean isEmpty(a){
        returnlinkList.isEmpty(); }}class Test13 {
    public static void main(String[] args) {
        / / test stack
        Test12 test12 = new Test12();
        test12.push("I was the first one in.");
        test12.push("I was the second one to go in.");
        test12.push("I was the third one to go in.");
        test12.push("I was the fourth to go in.");
        test12.push("I was the fifth to go in.");
        / / remove
        while(! test12.isEmpty()){ String pop = test12.pop(); System.out.println(pop); }// Print the result
        /* I was the fifth in, I was the fourth in, I was the third in, I was the second in, I was the first in */}}Copy the code

LinkedList implementation Queue:

package org.example.test;
import java.util.LinkedList;

/** * use linkedList to implement queue * queue: first in, first out */
public class Test12 {

    private LinkedList<String> link = new LinkedList<String>();
    / / in the
    public void put(String str) {
        link.addFirst(str);
    }

    / / to get
    public String get(a) {
        return link.removeLast();
    }

    // Check whether it is null
    public boolean isEmpty(a) {
        returnlink.isEmpty(); }}class Test13 {
    public static void main(String[] args) {
        // Test the queue
        Test12 queue = new Test12();
        queue.put("I was the first one in line.");
        queue.put("I was the second one in line.");
        queue.put("I was the third person in line.");
        queue.put("I was the fourth person in line.");
        // Walk through the queue
        while(! queue.isEmpty()) { String str = queue.get(); System.out.println(str); }// Print the result
        /* I'm the first in the queue, I'm the second in the queue, I'm the third in the queue, I'm the fourth in the queue */}}Copy the code

Vector:

Obsolete, replaced by ArrayList; It also has an iterator that is retrieved through vector.elements() to determine whether there are elements and hasMoreElements()nextElement() to which the element is taken.

public static void main(String[] args) {
    Vector<String> vector = new Vector<>();
    vector.add("a");
    vector.add("v");
    vector.add("d");
    Enumeration<String> elements = vector.elements();
    while(elements.hasMoreElements()) { String nextElement = elements.nextElement(); System.out.println(nextElement); }}Copy the code

There are also some basic operations:

public static void main(String[] args) {
    List<String> list = new ArrayList<String>();
    list.add("b");// the first index is 0
    list.add("d");// index subscript 1
    list.add("c");// index subscript 2
    list.add("a");// index subscript 3
    list.add("d");// Allow repeating elements

    System.out.println(list);// Result: [b, D, c, a, d]
    System.out.println(list.get(2));// Access the collection element at the specified location by index. Results: c

    list.add(1."f");// Inserts data at the specified index subscript
    System.out.println(list);// Result: [b, f, d, c, a, d]

    List<String> m = new ArrayList<String>();
    m.add("123");
    m.add("456");

    list.addAll(2, m);// Inserts the collection at the specified index subscript

    System.out.println(list);// Result: [b, f, 123, 456, d, c, a, d]

    System.out.println(list.indexOf("d"));// Gets the index of the first occurrence of the specified element in the collection. Results: 4
    System.out.println(list.lastIndexOf("d"));// Gets the index of the last occurrence of the specified element in the collection. Results: 7

    list.remove(2);// Removes elements based on the specified index subscript
    System.out.println(list);// Result: [b, f, 456, d, c, a, d]

    list.set(1."ff");// Modify the element according to the specified index subscript
    System.out.println(list);// Result: [b, ff, 456, d, c, a, d]

    // Intercepts a new set of element parameters at the starting position of the index subscript. When intercepting, the starting index does not contain the ending index
    List<String> sublist =  list.subList(2.4);// Index elements greater than or equal to 2 and less than 4

    System.out.println(sublist);[456, d]

    System.out.println(list.size());// Set length. Results: 7
}
Copy the code

Set a collection:

The Set sets are: HashSet, LinkedHashSet, TreeSet

The characteristics of Set: elements do not repeat, access disorder, no subscript

HashSet:

public static void main(String[] args) {
        // Use HashSet to access
        Set<String> set = new HashSet<String>();
        set.add("a");
        set.add("b");
        set.add("b");
        set.add("c");
        // Iterate over the first way iterator
        Iterator<String> it = set.iterator();
        while(it.hasNext()){
            String str = it.next();
            System.out.println(str);
        }

        System.out.println("-- -- -- -- -- -- -- -- -- -- -- -- -- -");
        for (String str : set){
            System.out.println(str);
        }
        // Print the result, duplicates have been removed
        /* a b c -------------- a b c*/
    }
Copy the code

A HashSet stores the elements of a collection using a Hash algorithm, so it has good access and lookup performance. HashSet has the following characteristics:

  • The order of elements cannot be guaranteed
  • Non-repeatable (different Hashcode)
  • Hashsets are not thread-safe
  • Collection elements can be null

When storing an element into a HashSet, the HashSet calls the object’s hashCode() method to get the object’s hashCode value, and then uses the hashCode value to determine where the object will be stored in the HashSet. Where the set exists is determined by the value’s Hashcode, not first come last. If two elements’ equals() returns true, but their hashCode() returns different values, the hashSet will store them in different locations but still add successfully.

Using HashSet to store custom objects:

package org.example.test;

public class Person {
    / / property
    private String name;
    private int age;

    // constructor
    public Person(a) {
        super(a); }public Person(String name, int age) {
        super(a);this.name = name;
        this.age = age;
    }

    // The hasCode and equals methods must be overridden to allow the hash table to store non-repeating elements
    @Override
    public int hashCode(a) {
        final int prime = 31;
        int result = 1;
        result = prime * result + age;
        result = prime * result + ((name == null)?0 : name.hashCode());
        return result;
    }

    @Override
    public boolean equals(Object obj) {
        if (this == obj)
            return true;
        if (obj == null)
            return false;
        if(getClass() ! = obj.getClass())return false;
        Person other = (Person) obj;
        if(age ! = other.age)return false;
        if (name == null) {
            if(other.name ! =null)
                return false;
        } else if(! name.equals(other.name))return false;
        return true;
    }


    @Override
    public String toString(a) {
        return "Person [name=" + name + ", age=" + age + "]";
    }
    // getter & setter


    public String getName(a) {
        return name;
    }

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

    public int getAge(a) {
        return age;
    }

    public void setAge(int age) {
        this.age = age; }}Copy the code
 public static void main(String[] args) {
     // Use HashSet to access the custom object Person
     Set<Person> set = new HashSet<Person>();

     set.add(new Person("Zhang".12));
     set.add(new Person("Bill".13));
     set.add(new Person("Fifty".22));
     set.add(new Person("Zhang".12));

     / / traverse
     for (Person p : set){
         System.out.println(p);
     }
     // Result: Two objects are stored in the collection, but one object is successfully stored in the collection
     /*Person [name= name, age=22] Person [name= name, age=12]*/
}
Copy the code

So when storing custom objects into a HashSet, the hashCode and equals methods must be overridden to ensure that the set is unique.

LinkedHashSet:

Is based on linked list and hash table common implementation, so have access to order, the element is unique

public static void main(String[] args) {
    // Use LinkedHashSet to access the custom object Person
    LinkedHashSet<Person> set = new LinkedHashSet<Person>();
    set.add(new Person("Zhang".12));
    set.add(new Person("Bill".13));
    set.add(new Person("Fifty".22));
    set.add(new Person("Zhang".12));
    / / traverse
    for (Person p : set){
        System.out.println(p);
    }
    // Result: Two objects are stored in the set, but one object is successfully stored in the set.
    // The order in which you put them is the same as the order in which you take them out
    /*Person [name, age, age] Person [name, age, age, age]*/
}
Copy the code

TreeSet:

  • TreeSet is an implementation class of the SortedSet interface

  • TreeSet features: Unordered access, unique elements, and sorting (sorting is done when adding)

  • TreeSet supports two sorting methods: natural and custom. By default, TreeSet uses natural sorting

The TreeSet collection stores strings

  public static void main(String[] args) {
        TreeSet<String> treeSet = new TreeSet<String>();
        treeSet.add("a");
        treeSet.add("c");
        treeSet.add("d");
        treeSet.add("b");

        for (String str : treeSet){
            System.out.println(str);
        }
        // Result: The extracted result is sorted
        /* a b c d*/
    }
Copy the code

TreeSet guarantees element uniqueness in two ways:

Comparable (0, 0); Comparable (0, 0); Comparable (0, 0);

When TreeSet is created, we pass the Comparator interface implementation object into the constructor. The implementation of the Comparator interface overrides the compara method.

A ClassCastException occurs when a custom object is saved to TreeSet and the custom class does not implement the Comparable interface, or when a Comparator is not passed in.

Here are two ways to store custom objects

package org.example.test;

import java.util.TreeSet;

public class Person implements Comparable<Person> {
    / / property
    private String name;
    private int age;

    // constructor
    public Person(a) {
        super(a); }public Person(String name, int age) {
        super(a);this.name = name;
        this.age = age;
    }

    // The hasCode and equals methods must be overridden to allow the hash table to store non-repeating elements
    @Override
    public int hashCode(a) {
        final int prime = 31;
        int result = 1;
        result = prime * result + age;
        result = prime * result + ((name == null)?0 : name.hashCode());
        return result;
    }

    @Override
    public boolean equals(Object obj) {
        if (this == obj)
            return true;
        if (obj == null)
            return false;
        if(getClass() ! = obj.getClass())return false;
        Person other = (Person) obj;
        if(age ! = other.age)return false;
        if (name == null) {
            if(other.name ! =null)
                return false;
        } else if(! name.equals(other.name))return false;
        return true;
    }


    @Override
    public String toString(a) {
        return "Person [name=" + name + ", age=" + age + "]";
    }
    // getter & setter


    public String getName(a) {
        return name;
    }

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

    public int getAge(a) {
        return age;
    }

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

    @Override
    public int compareTo(Person o) {
        int result = this.age - o.age;
        if (result == 0) {
            return this.name.compareTo(o.name);
        }
        return result;
    }


    public static void main(String[] args) {
        // Use TreeSet to store custom Person objects
        TreeSet<Person> treeSet = new TreeSet<Person>();
        The Person class implements the Comparable interface and overrides the comparaTo method
        // The comparison rules are sorted by age first, and the comparison rules are sorted by name
        treeSet.add(new Person("Zhang shan 1".20));
        treeSet.add(new Person("Zhang shan 2".16));
        treeSet.add(new Person("Zhang shan 3".13));
        treeSet.add(new Person("Zhang shan four.".17));
        treeSet.add(new Person("Zhang shan 5".20));
        for (Person p : treeSet) {
            System.out.println(p);
        }
        // Result: Sort according to the logic in the comparaTo method
        /* Person [name= name, age=13] Person [name= name, age=16] Person [name= name, age=17] Person [name= name, age=17] Person [name= name, age=17] Person [name= name, age=17] Person [name= name, age=20] */}}Copy the code

Another way: use the Comparator

package org.example.test; import java.util.Comparator; import java.util.TreeSet; Public class Person {// attribute private String name; private int age; Constructor public Person() {super(); } public Person(String name, int age) { super(); this.name = name; this.age = age; Override public int hashCode() {final int prime = 31; int result = 1; result = prime * result + age; result = prime * result + ((name == null) ? 0 : name.hashCode()); return result; } @Override public boolean equals(Object obj) { if (this == obj) return true; if (obj == null) return false; if (getClass() ! = obj.getClass()) return false; Person other = (Person) obj; if (age ! = other.age) return false; if (name == null) { if (other.name ! = null) return false; } else if (! name.equals(other.name)) return false; return true; } @Override public String toString() { return "Person [name=" + name + ", age=" + age + "]"; } // getter & setter 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; } public static void main(String[] args) {public static void main(String[] args) {public static void main(String[] args) { Using anonymous inner classes // The comparison rules are sorted by age first, TreeSet<Person> TreeSet = new TreeSet<Person>(new Comparator<Person>() {@override public int compare(Person o1, Person o2) { if (o1 == o2){ return 0; } int result = o1.getAge() - o2.getAge(); if (result == 0){ return o1.getName().compareTo(o2.getName()); } return result; }}); Treeset. add(new Person(" zhangshan 1", 20)); Treeset. add(new Person(" zhangshan 2", 16)); Treeset. add(new Person(" zhangshan 3", 13)); Treeset. add(new Person(" zhangshan 4", 17)); Treeset. add(new Person(" zhangshan 5", 20)); for (Person p : treeSet){ System.out.println(p); } // Result: /* Person [name= js1, age=13] Person [name= js1, age=16] Person [name= js1, age=17] Person [name= name, age=20] */}}Copy the code

3. Map set

Below the Map collection are the HashMap, LinkedHashMap, and TreeMap

  • A Map is used to store two sets of mapped data. One set of values is used to store the keys in the Map, and the other set is used to store the values in the Map

  • Both keys and values in a Map can be data of any reference type

  • Keys in a Map cannot be duplicated, that is, any two keys of the same Map object return false through the equals method

  • There is a one-way one-to-one relationship between Key and Value, that is, a unique and definite Value can always be found through the specified Key.

HashMap:

Is implemented based on a hash table structure, so when storing custom objects as keys, you must override hasCode and equals methods to access unordered.

Here’s how HashMap uses custom objects as keys:

public static void main(String[] args) {
    // Use a HashMap store, with a custom object Person as the key
    // To ensure key uniqueness, we must override hashCode and equals methods
    HashMap<Person,String> map = new HashMap<Person,String>();
    map.put(new Person("Zhang".12), "JAVA");
    map.put(new Person("Bill".13), "IOS");
    map.put(new Person("Flower".22), "JS");
    map.put(new Person("Black".32), "PHP");
    map.put(new Person("Zhang".12), "C++");
    Set<Entry<Person, String>> entrySet = map.entrySet();
    Iterator<Entry<Person, String>> it = entrySet.iterator();
    while (it.hasNext()){
        Entry<Person, String> entry = it.next();
        System.out.println(entry.getKey() + "-" + entry.getValue());
    }
    // Result: two threes were added when the Map was stored. If the keys in the Map are the same, the later values will overwrite the previous values
    /* Person [name= Person, age=13]-- IOS Person [name= Person, age=12]-- C++ Person [name= Person, age=32]-- PHP Person [name= Person, age=22]---JS */
}
Copy the code

LinkedHashMap:

The usage is basically the same as HashMap. It is based on the structure of linked list and hash table, so it has the characteristics of orderly access and non-duplicate keys.

The following example uses LinkedHashMap storage, noting that the order of storage is the same as the order of traversal:

public static void main(String[] args) {
    // Use the LinkedHashMap store to define the Person object as the key
    // To ensure key uniqueness, we must override hashCode and equals methods
    LinkedHashMap<Person,String> map = new LinkedHashMap<Person,String>();

    map.put(new Person("Zhang".12), "JAVA");
    map.put(new Person("Bill".13), "IOS");
    map.put(new Person("Flower".22), "JS");
    map.put(new Person("Black".32), "PHP");
    map.put(new Person("Zhang".12), "C++");

    / / foreach traversal
    for (Entry<Person,String> entry : map.entrySet()){
        System.out.println(entry.getKey()+"= = ="+entry.getValue());
    }
    // Result: two threes were added when the Map was stored. If the keys in the Map are the same, the later values will overwrite the previous values
    // Note: LinkedHashMap is characterized by orderly access, the order in which it is taken out is the same as that in which it is saved
    /* Person [name= name, age=12]== C++ Person [name= name, age=13]===IOS Person [name= small, age=22]===JS Person [name= small, age=22]=== small, age=32]===PHP */
}
Copy the code

TreeMap:

Save a custom object to the TreeMap collection. The custom object is used as the key of the TreeMap collection. Due to the binary tree used at the bottom of TreeMap, all data stored in TreeMap need to be sorted. To sort, objects are required to have comparison function. The class to which the object belongs needs to implement the Comparable interface. Or pass a Comparator interface object to the TreeMap collection.

Use TreeMap to store custom objects as keys:

public static void main(String[] args) {
    // Use TreeMap storage to customize the object Person as the key
    // Custom objects implement the Comparable interface or pass in the Comparator
    TreeMap<Person,String> map = new TreeMap<Person,String>(new Comparator<Person>() {
        @Override
        public int compare(Person o1, Person o2) {
            if (o1 == o2){
                return 0;
            }
            int result = o1.getAge() - o2.getAge();
            if (result == 0) {return o1.getName().compareTo(o2.getName());
            }
            returnresult; }}); map.put(new Person("Zhang".12), "JAVA");
    map.put(new Person("Bill".50), "IOS");
    map.put(new Person("Flower".32), "JS");
    map.put(new Person("Black".32), "PHP");
    map.put(new Person("Zhang".12), "C++");

    / / foreach traversal
    for (Entry<Person,String> entry : map.entrySet()){
        System.out.println(entry.getKey()+"= = ="+entry.getValue());
    }
    // Result: two threes were added when the Map was stored. If the keys in the Map are the same, the later values will overwrite the previous values
    // Note that TreeMap retrievals are sorted according to the compara method
    /* Person [name= name, age=12]== C++ Person [name= small, age=32]===JS Person [name= small, age=32]===PHP Person [name= small, age=32]===PHP Person [name= small, age=32]===PHP Person [name= small, age=32]=== age=50]===IOS */
}
Copy the code

At the end

I am a coder who is being beaten and still trying to move on. If this article is helpful to you, remember to like and follow yo, thanks!