Java collection framework

aggregate

Set concept

Object, which realizes the common operations on objects, similar to the array function.

The difference between sets and arrays

  1. The array length is fixed and the collection length is not fixed
  2. Arrays can store basic data types and reference types, and collections can only reference types

iterator

Concept: a way of traversing a collection
hasNext(); Is there a next element? If yes, it returns true; otherwise, it returns false
next(); Get next element
remove(); Delete element

package com.xiang.collection;

import java.util.ArrayList;
import java.util.Collection;
import java.util.Iterator;

/*
collection Interface use
1.Add element
2.Delete element
3.Traversal element
4.judge
 */
public class Collection01 {
    public static void main(String[] args) {
        //Create a collection
        Collection collection = new ArrayList();

//        1. Add elements
        collection.add("Apple");
        collection.add("watermelon");
        collection.add("Durian");
        System.out.println("Number of elements:"+collection.size());
        System.out.println(collection);

//        2. Delete element
//        collection.remove("Durian");
//        collection.clear();
//        System.out.println("number of elements:" + collection.size());

//        3. Traverse elements [key]
        // 3.1 using enhanced for
        System.out.println("===========3.1 enhance for===========");
        for (Object object : collection) {
            System.out.println(object);
        }
        //3.2 using iterators (a method that iterators specifically use to traverse collections)
        //hasNext(); Is there a next element
        //next(); Get next element
        //remove(); Delete current element
        System.out.println("===========3.2 Using Iterators ===========");
        Iterator it =collection.iterator();
        while (it.hasNext()){
            String s =(String) it.next();
            System.out.println(s);
            //The collection. Method cannot be deleted using collection remove(s);
//            it.remove();
        }
        System.out.println("Number of elements:"+collection.size());

//        4. Judgment
        System.out.println("===========judge===========");
        System.out.println(collection.contains("watermelon"));
        System.out.println(collection.isEmpty());


    }

}
package com.xiang.collection;

import java.util.ArrayList;
import java.util.Collection;
import java.util.Iterator;

/*
Collection Use of: save student information
 */
public class Collection02 {
    public static void main(String[] args) {
        //New Collection object
        Collection collection=new ArrayList();
        Student s1 =new Student("Zhang San",20);
        Student s2 =new Student("Li Si",18);
        Student s3 =new Student("Wang Wu",22);

        //1. Add data
        collection.add(s1);
        collection.add(s2);
        collection.add(s3);
        System.out.println("Number of elements:"+collection.size());
        System.out.println(collection.toString());
        //2. Delete
//        collection.remove(s1);
//        collection.remove(new Student("Wang Wu", 22));
//        collection.clear();
//        System.out.println("after deletion:" + collection.size());

        //3 traversal
        //3.1 enhanced for
        System.out.println("=====enhance for======");
        for (Object object:collection) {
            Student s= (Student) object;
            System.out.println(s.toString());
        }
        //3.2 iterator: hasNext(); next(); remove(); The deletion method of collection cannot be used during iteration
        System.out.println("=====iterator ======");
        Iterator it=collection.iterator();
        while (it.hasNext()){
            Student s = (Student) it.next();
            System.out.println(s.toString());
        }

        System.out.println("=====judge======");
        System.out.println(collection.contains(s1));
        System.out.println(collection.isEmpty());
    }
}

List

Features of List interface

Ordered, subscript, repeatable

package com.xiang.collection;

import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.ListIterator;

/*
List Use of sub interfaces
 Features 1 Ordered with subscript 2 Can repeat
 */
public class List1 {
    public static void main(String[] args) {
        //Create the collection object first
        List list =new ArrayList();
        //1. Add elements
        list.add("Apple");
        list.add("millet");
        list.add(0,"Huawei");
        System.out.println("Number of elements:"+list.size());
        System.out.println(list.toString());

        //2. Delete element
//        list.remove("apple");
//        list.remove(0);
//        System.out.println("after deletion:" + list.size());
//        System.out.println(list.toString());

        //3. Traversal
        //3.1 using for traversal
        System.out.println("=====3.1 use for ergodic======");
        for (int i = 0; i < list.size(); i++) {
            System.out.println(list.get(i));
        }
        //3.2 using enhanced for
        System.out.println("=====3.2 Use enhancements for ergodic======");
        for (Object object:list) {
            System.out.println(object);
        }
        //3.3 using iterators
        System.out.println("=====3.3 Traversal using iterators======");
        Iterator it = list.iterator();
        while (it.hasNext()){
            System.out.println(it.next());
        }
        //3.4 using list iterators
        System.out.println("=====3.4 Use the list iterator to traverse from front to back======");
        ListIterator lit = list.listIterator();
        while (lit.hasNext()){
            System.out.println(lit.nextIndex()+":"+lit.next());
        }
        System.out.println("=====3.4 Use the list iterator to iterate back and forth======");
        while (lit.hasPrevious()){
            System.out.println(lit.previousIndex()+":"+lit.previous());
        }

        //4. Judgment
        System.out.println("=====4.judge======");
        System.out.println(list.contains("Apple"));
        System.out.println(list.isEmpty());

        //5 get location
        System.out.println(list.indexOf("Huawei"));
    }
}

package com.xiang.collection;

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

public class List2 {
    public static void main(String[] args) {
        //Create collection
        List list =new ArrayList();
        //1. Add digital data
        list.add(20);
        list.add(30);
        list.add(40);
        list.add(50);
        list.add(60);
        System.out.println("Number of elements:"+list.size());
        System.out.println(list.toString());

        //2. Delete
//        list.remove((Object) 20);
//        list.remove(new Integer(20));
//        System.out.println("number of elements after deletion:" + list.size());
//        System.out.println(list.toString());

        //3. The supplementary method subList returns a subset
        List subList = list.subList(1, 3);
        System.out.println(subList.toString());
    }
}

List common implementation classes

ArrList:

Array structure implementation, fast query, slow addition and deletion

Source code analysis:

  • DEFAULT_CAPACITY = 10; Default capacity
    (if no element is added to the collection, the capacity is 0)
    (after adding an element, the capacity is 10)
    (the size of each expansion is 1.5 times of the original)
  • elementDate an array of elements
  • size actual number of elements
  • add(); Add element
package com.xiang.collection;

import java.util.ArrayList;
import java.util.Iterator;
import java.util.ListIterator;

/*
ArrayList Use of
    Storage structure: array, fast search and traversal speed, slow addition and deletion
 */
public class ArrayList1 {
    public static void main(String[] args) {
        //Create collection
        ArrayList arrayList = new ArrayList();
        //1. Add elements
        Student s1= new Student("Lau Andy",20);
        Student s2= new Student("Guo Fucheng",22);
        Student s3= new Student("Chao Wei Liang",18);
        arrayList.add(s1);
        arrayList.add(s2);
        arrayList.add(s3);
        System.out.println("Number of elements:"+arrayList.size());
        System.out.println(arrayList.toString());

        //2. Delete element
//        arrayList.remove(new Student("Andy Lau, 20));
//        System.out.println("number of deleted elements:" + arrayList.size());

        //3. Traverse elements [key]
        //3.1 using iterators
        System.out.println("======3.1 Using Iterators ========");
        Iterator it = arrayList.iterator();
        while (it.hasNext()){
            Object s = it.next();
            System.out.println(s.toString());
        }
        //3.2 using list iterators
        ListIterator lit = arrayList.listIterator();
        System.out.println("======3.2 Using list iterators========");
        while (lit.hasNext()){
            Object s = lit.next();
            System.out.println(s.toString());
        }
        System.out.println("======3.2 Using list iterators(Reverse order)========");
        while (lit.hasPrevious()){
            Object s = lit.previous();
            System.out.println(s.toString());
        }

        //4. Judgment
        System.out.println(arrayList.contains(s1));
        System.out.println(arrayList.isEmpty());

        //5. Find
        System.out.println(arrayList.indexOf(s1));
    }
}

Vector:

Array structure implementation, fast query, slow addition and deletion

package com.xiang.collection;

import java.util.Enumeration;
import java.util.Iterator;
import java.util.ListIterator;
import java.util.Vector;

/*
Vector Use of collections
 Storage structure: array
 */
public class VectorA {
    public static void main(String[] args) {
        //Create collection
        Vector vector = new Vector();
        //1. Add elements
        vector.add("strawberry");
        vector.add("Mango");
        vector.add("watermelon");
        System.out.println("Number of elements:" + vector.size());
        System.out.println(vector.toString());
        //2. Delete element
//        vector.remove(0);
//        vector.remove("watermelon");
//        vector.clear();
//        System.out.println(vector.toString());

        //3. Traversal
        //3.1 using enumerator
        Enumeration en = vector.elements();
        System.out.println("===============");
        while (en.hasMoreElements()) {
            Object o = en.nextElement();
            System.out.println(o);
        }
        //3.2 using iterators
        Iterator it = vector.iterator();
        System.out.println("===============");

        while (it.hasNext()) {
            Object o = it.next();
            System.out.println(o);
        }
        //3.3 using List iterators
        System.out.println("===============");

        ListIterator lit = vector.listIterator();
        while (lit.hasNext()) {
            Object o = lit.next();
            System.out.println(o.toString());
        }
        //3.4 enhanced for
        for (Object object : vector) {
            System.out.println(object);
        }

        //4. Judgment
        System.out.println(vector.contains("watermelon"));
        System.out.println(vector.isEmpty());

        //5. Other methods
        System.out.println(vector.firstElement());
        System.out.println(vector.lastElement());
        System.out.println(vector.elementAt(2));
    }
}


LinkedList:

Implementation of linked list structure, slow query, fast addition and deletion

  • int size; The size of the collection
  • Node first; Head node of linked list
  • Node last; Tail node of linked list
package com.xiang.collection;

import java.util.Iterator;
import java.util.LinkedList;
import java.util.ListIterator;

/*
LinkedList Use of
 Storage structure: bidirectional linked list
 */
public class LinkedList1 {
    public static void main(String[] args) {
        //Create collection
        LinkedList linkedList = new LinkedList();

        //1. Add elements
        Student s1= new Student("Lau Andy",20);
        Student s2= new Student("Guo Fucheng",22);
        Student s3= new Student("Chao Wei Liang",18);

        linkedList.add(s1);
        linkedList.add(s2);
        linkedList.add(s3);
        System.out.println("Number of elements:"+linkedList.size());
        System.out.println(linkedList.toString());

        //2. Delete
//        linkedList.remove(s2);
//        linkedList.remove(0);
//        linkedList.remove(new Student("Andy Lau, 20));
//        linkedList.clear();
//        System.out.println("number of elements after deletion is:" + linkedList.size());

        //3. Traversal
        //3.1 using for traversal
        System.out.println("==============use for ergodic============");
        for (int i = 0; i <linkedList.size(); i++) {
            System.out.println(linkedList.get(i));
        }
        //3.2 using enhanced for traversal
        System.out.println("==============Use enhancements for ergodic============");
        for (Object object: linkedList   ) {
            Object o = object;
            System.out.println(o.toString());
        }
        //3.3 using iterators
        System.out.println("===============Using Iterators ============");
        Iterator it=linkedList.iterator();
        while (it.hasNext()){
            Object o = it.next();
            System.out.println(o.toString());
        }
        //3.3 using list iterators
        System.out.println("===============Using list iterators============");
        ListIterator lit = linkedList.listIterator();
        while (lit.hasNext()){
            Object o = lit.next();
            System.out.println(o.toString());
        }
        System.out.println("===============Using list iterators(Reverse order)============");
        while (lit.hasPrevious()){
            Object o = lit.previous();
            System.out.println(o.toString());
        }

        //4. Judgment
        System.out.println(linkedList.contains(s1));
        System.out.println(linkedList.isEmpty());

        //5. Access
        System.out.println(linkedList.indexOf(s2));
    }
}

generic paradigm

  • Java generics are jdk1 A new feature introduced in 5, whose essence is parameterized types, which are passed as parameters.
  • Common forms include generic classes, generic interfaces, and generic methods.
  • Syntax:
    • < T,... > t is called a type placeholder and represents a reference type
  • Benefits:
    • (1) Improve code reusability
    • (2) Prevent type conversion exceptions and improve code security
package com.xiang.generic;
/*
Generic class
 Syntax: class name < T,... >
T Is a type placeholder that represents a reference type. If you write multiple, separate them with
 */
public class MyGeneric<T> {
    //Use generic T
    //1. Create variables
    T t;

    //2. As a parameter of the method
    public void show(T t){
        System.out.println(t);
    }

    //3. Use generics as the return value of the method
    public T getT(){
        return t;
    }
}

package com.xiang.generic;
/*
generic interface 
Syntax: interface name < T >
Note: you cannot use generics to create static constants
 */
public interface MyInterface<T> {
    String name ="Zhang San";

    T server(T t);
}
package com.xiang.generic;
/*
generic method 
Syntax: < T > return value type
 */
public class MyGenericMethod {

    //generic method 
    public <T> T  show(T t){
        System.out.println("generic method "+t);
        return t;

    }

}

package com.xiang.generic;

public class MyInterfaceImpl implements MyInterface<String>{

    @Override
    public String server(String t) {
        System.out.println(t);
        return t;
    }
}

package com.xiang.generic;

public class MyInterfaceImpl2<T> implements MyInterface<T>{
    @Override
    public T server(T t) {
        System.out.println(t);
        return t;
    }
}

Test:

package com.xiang.generic;

public class TestGeneric {
    public static void main(String[] args) {
        //Creating objects using generic classes
        //Note: 1 Generic types can only use reference type 2 Different generic objects cannot be assigned to each other
        MyGeneric<String> myGeneric =new MyGeneric<String>();
        myGeneric.t="hello";
        myGeneric.show("Hello everyone, come on");
        String string = myGeneric.getT();
        System.out.println(string);

        MyGeneric<Integer> myGeneric1=new MyGeneric<Integer>();
        myGeneric1.t=100;
        myGeneric1.show(200);
        Integer integer = myGeneric1.getT();
        System.out.println(integer);

        //generic interface 
        MyInterfaceImpl impl=new MyInterfaceImpl();
        impl.server("xxxxx");

        MyInterfaceImpl2<Integer> impl2=new MyInterfaceImpl2<>();
        impl2.server(1000);

        //generic method 
        MyGenericMethod myGenericMethod=new MyGenericMethod();
        myGenericMethod.show("lbwnb");
        myGenericMethod.show(200);
        myGenericMethod.show(3.14);


    }
}

Set implementation class

package com.xiang.set;
/*
Test the use of Set interface
 Features: (1) disorder, no subscript (2) cannot be repeated
 */

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

public class Set01 {
    public static void main(String[] args) {
        //Create collection
        Set<String> set =new HashSet<>();
        //1. Add data
        set.add("Apple");
        set.add("Huawei");
        set.add("millet");
        System.out.println("Number of data:"+set.size());
        System.out.println(set.toString());

        //2. Delete data
//        set.remove("Xiaomi");
//        System.out.println(set.toString());
        
        //3. Traversal
        //3.1 enhanced for
        System.out.println("======enhance for======");
        for (String string:set
             ) {
            System.out.println(string);
        }
        //3.2 using iterators
        System.out.println("======iterator ======");
        Iterator<String> it = set.iterator();
        while (it.hasNext()){
            String s = it.next();
            System.out.println(s);
        }
        //4. Judgment
        System.out.println(set.contains("Huawei"));
        System.out.println(set.isEmpty());
    }
}

HashSet [ key ]

  • Calculate element storage location based on HashCode
  • When the hashes of the stored elements are the same, equals will be called for confirmation. If the result is true, the latter will be rejected.
package com.xiang.set;

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

/**
 * HashSet Use of collections
 * Storage structure: hash table (array + linked list + red black tree)
 */
public class HashSet01 {
    public static void main(String[] args) {
        //New collection
        HashSet<String> hashSet =new HashSet<>();
        //1. Add elements
        hashSet.add("Lau Andy");
        hashSet.add("Chao Wei Liang");
        hashSet.add("Lin Zhiling");
        hashSet.add("Zhou Runfa");

        System.out.println("Number of elements:"+hashSet.size());
        System.out.println(hashSet.toString());

        //2. Delete data
//        hashSet.remove("Andy Lau");
//        System.out.println("number of elements after deletion:" + hashSet.size());

        //3. Traversal operation
        //3.1 enhanced for
        System.out.println("======enhance for=======");
        for (String string:hashSet
             ) {
            System.out.println(string);
        }

        //3.2 iterators
        Iterator<String> it = hashSet.iterator();
        System.out.println("========iterator =========");
        while (it.hasNext()){
            System.out.println(it.next());
        }
        //4 judgment
        System.out.println(hashSet.contains("Guo Fucheng"));
        System.out.println(hashSet.isEmpty());

    }
}

package com.xiang.set;

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

/**
 * HashSet Use of
 * Storage structure: hash table (array + linked list + red black tree)
 * Stored procedure:
 * 1.Calculate the saved location according to hashcode. If this location is empty, it will be saved directly. If it is not empty, proceed to step 2
 * 2.Then execute the equals method. If the equals method is true, it is considered to be a duplicate. Otherwise, a linked list is formed
 */
public class HashSet02 {

    public static void main(String[] args) {
        //Create collection
        HashSet<Person> persons = new HashSet<>();
        //1 add data
        Person p1=new Person("Lau Andy",20);
        Person p2=new Person("Lin Zhiling",18);
        Person p3=new Person("Chao Wei Liang",22);

        persons.add(p1);
        persons.add(p2);
        persons.add(p3);
        persons.add(new Person("Chao Wei Liang",22));
        System.out.println("Number of elements:"+persons.size());
        System.out.println(persons.toString());

        //2. Delete data
//        person.remove(p1);
//        person.clear();
//        System.out.println("number of elements after deletion:" + person.size());

        //3. Traversal
        //3.1 enhanced for
        System.out.println("=====enhance for=====");

        for (Person person : persons) {
            System.out.println(person.toString());
        }

        //3.2 using iterators
        System.out.println("=====iterator =====");
        Iterator<Person> it = persons.iterator();
        while (it.hasNext()){
            System.out.println(it.next());
        }
        //4. Judgment
        System.out.println(persons.contains(new Person("Lau Andy",20)));
        System.out.println(persons.isEmpty());
    }
}

package com.xiang.set;

import java.util.Objects;

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

    public Person(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 String toString() {
        return "Person{" +
                "name='" + name + '\'' +
                ", age=" + age +
                '}';
    }
//
//    @Override
//    public int hashCode() {
//        int n1=this.name.hashCode();
//        int n2=this.age;
//
//        return n1+n2;
//    }
//
//    @Override
//    public boolean equals(Object obj) {
//        if (this==obj){
//            return true;
//        }
//        if (obj==null){
//            return false;
//        }
//        if (obj instanceof Person){
//            Person p = (Person) obj;
//            if (this.name.equals(p.getName())&&this.age==p.getAge()){
//                return true;
//            }
//        }
//        return false;
//    }

    @Override
    public boolean equals(Object o) {
        if (this == o) return true;
        if (!(o instanceof Person)) return false;
        Person person = (Person) o;
        return getAge() == person.getAge() && Objects.equals(getName(), person.getName());
    }

    @Override
    public int hashCode() {
        return Objects.hash(getName(), getAge());
    }

    //First by name, then by age
    @Override
    public int compareTo(Person o) {
        int n1 = this.getName().compareTo(o.getName());
        int n2=this.age-o.getAge();

        return n1==0?n2:n1;
    }
}

TreeSet

  • Non repetition of elements based on arrangement order
  • The SortedSet interface is implemented to automatically sort the set elements
  • The type of the element object must implement the Comparable interface and specify the collation
  • Determine whether it is a duplicate element through the CompareTo method
package com.xiang.set;

import java.util.Iterator;
import java.util.TreeSet;

/**
 * TreeSet Use of
 * Storage structure: red black tree
 */
public class TreeSet01 {

    public static void main(String[] args) {
        //Create collection
        TreeSet<String> treeSet=new TreeSet<>();
        //1. Add elements
        treeSet.add("xyz");
        treeSet.add("abc");
        treeSet.add("hello");

        System.out.println("Number of elements:"+treeSet.size());
        System.out.println(treeSet.toString());

        //2. Delete element
//        treeSet.remove("xyz");
//        System.out.println("after deletion:" + treeSet.size());

        //3 traversal
        //3.1 enhanced for
        System.out.println("------enhance for-------");
        for (String string :treeSet
             ) {
            System.out.println(string);
        }
        //3.2 iterators
        System.out.println("------iterator -------");
        Iterator<String> it = treeSet.iterator();
        while (it.hasNext()){
            System.out.println(it.next());
        }

        //4. Judgment
        System.out.println(treeSet.contains("abc"));
        System.out.println(treeSet.isEmpty());
    }
}
package com.xiang.set;

import java.util.Iterator;
import java.util.TreeSet;

/**
 * Save data using TreeSet01
 * Storage structure: red black tree
 * Requirement: the element must implement the Comparable interface
 */
public class TreeSet02 {
    public static void main(String[] args) {
        //Create collection
        TreeSet<Person> persons=new TreeSet<>();
        //1. Add elements
        Person p1=new Person("xyz",20);
        Person p2=new Person("hello",18);
        Person p3=new Person("zhangsan",22);

        persons.add(p1);
        persons.add(p2);
        persons.add(p3);
        System.out.println("Number of elements:"+persons.size());
        System.out.println(persons.toString());

        //2. Delete
//        persons.remove(new Person("zhangsan",22));
//        System.out.println(persons.size());
        //3 traversal
        //3.1 enhanced for
        System.out.println("------enhance for-------");
        for (Person person :persons
        ) {
            System.out.println(person);
        }
        //3.2 iterators
        System.out.println("------iterator -------");
        Iterator<Person> it = persons.iterator();
        while (it.hasNext()){
            System.out.println(it.next());
        }
        //4. Judgment
        System.out.println(persons.contains(p1));
    }
}

package com.xiang.set;

import java.util.Comparator;
import java.util.TreeSet;

/**
 * TreeSet Use of collections
 * Comparator : Implement custom comparison (comparator)
 * Comparable Comparable
 */
public class TreeSet03 {
    public static void main(String[] args) {
        //Create a collection and specify comparison rules
        TreeSet<Person> persons=new TreeSet<>(new Comparator<Person>() {
            @Override
            public int compare(Person o1, Person o2) {
                int n1 =o1.getAge()-o2.getAge();
                int n2 = o1.getName().compareTo(o2.getName());

                return n1==0?n2:n1;
            }
        });
        Person p1=new Person("xyz",20);
        Person p2=new Person("hello",22);
        Person p3=new Person("zhangsan",25);
        Person p4=new Person("lisi",25);

        persons.add(p1);
        persons.add(p2);
        persons.add(p3);
        persons.add(p4);
        System.out.println("Number of elements:"+persons.size());
        System.out.println(persons.toString());


    }
}

package com.xiang.set;

import java.util.Comparator;
import java.util.TreeSet;

/**
 * Requirement: use TreeSet set to sort strings by length
 * helloword zhang lisi wangwu beijing xian nanjing
 * Comparator Interface implementation customization comparison
 */
public class TreeSet04 {
    public static void main(String[] args) {
        //Create a collection and specify comparison rules
        TreeSet<String> treeSet=new TreeSet<>(new Comparator<String>() {
            @Override
            public int compare(String o1, String o2) {
                int n1=o1.length()-o2.length();
                int n2=o1.compareTo(o2);
                return n1==0?n2:n1;
            }
        });
        //Add data
        treeSet.add("helloword");
        treeSet.add("zhang");
        treeSet.add("lisi");
        treeSet.add("wangwu");
        treeSet.add("beijing");
        treeSet.add("cat");
        treeSet.add("xian");
        treeSet.add("nanjing");

        System.out.println(treeSet.toString());


    }

}

Map collection

characteristic:

  1. Store key value pairs
  2. The key cannot be repeated, and the value can be repeated
  3. disorder
package com.xiang.map;

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

/**
 * Map Use of interfaces
 * Features 1 Store key value pair 2 Key cannot be repeated 3 disorder
 */
public class Map01 {
    public static void main(String[] args) {
        //Create a Map collection
        Map<String,String> map =new HashMap<>();
        //1. Add elements
        map.put("cn","China");
        map.put("uk","britain");
        map.put("usa","U.S.A");

        System.out.println("Number of elements:"+map.size());
        System.out.println(map.toString());

        //2. Delete
//        map.remove("usa");
//        System.out.println(map.toString());

        //3 traversal
        //3.1 use keySet();
        System.out.println("======keySet()=====");
//        Set<String> keyset=map.keySet();
        for (String key:map.keySet()
             ) {
            System.out.println(key+map.get(key));
        }
        //3.2 use entrySet();
        System.out.println("======entrySet()=====");
        Set<Map.Entry<String, String>> entries = map.entrySet();
        for (Map.Entry<String,String> entry:entries
             ) {
            System.out.println(entry.getKey()+entry.getValue());
        }

        //4. Judgment
        System.out.println(map.containsKey("cn"));
        System.out.println(map.containsValue("Thailand"));


    }
}

HashMap

  1. Storage structure: hash table
  2. Repeat by: hashCode() method and equals method of key
package com.xiang.map;

import java.util.HashMap;
import java.util.Map;

/**
 * HashMap Use of collections
 * Storage structure: hash table (array + linked list + red black tree)
 * Use key and hashcode and equals as duplicates
 */
public class HashMap01 {
    public static void main(String[] args) {
        //Create collection
        HashMap<Student, String> students = new HashMap<Student, String>();
        //No element table = null size = 0 was added after hashmap was created to save space
        //1. Add elements
        Student s1=new Student("Sun WuKong",100);
        Student s2=new Student("Zhu Bajie",101);
        Student s3=new Student("Sha Wujing",102);
        students.put(s1,"Beijing");
        students.put(s2,"Shanghai");
        students.put(s3,"Hangzhou");
//        students.put(new Student("shawujing", 102), "Nanjing");

        System.out.println("Number of elements:"+students.size());
        System.out.println(students.toString());

        //2. Delete
//        students.remove(s1);
//        System.out.println("after deletion:" + students.size());

        //3 traversal
        //3.1 use keySet();
        System.out.println("====keySet====");
        for (Student key :
             students.keySet()) {
            System.out.println(key.toString()+students.get(key));
        }
        //3.2 use entrySet();
        System.out.println("==entrySet===");
        for (Map.Entry<Student,String> entry: students.entrySet()) {
            System.out.println(entry.getKey()+entry.getValue());
        }

        //4 judgment
        System.out.println(students.containsKey(s1));
        System.out.println(students.containsValue("Hangzhou"));
        System.out.println(students.isEmpty());
    }
}

package com.xiang.map;

import java.util.Objects;

public class Student implements Comparable<Student>{
    private String name;
    private int stuNo;

    public Student(){

    }

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

    public String getName() {
        return name;
    }

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

    public int getStuNo() {
        return stuNo;
    }

    public void setStuNo(int stuNo) {
        this.stuNo = stuNo;
    }

    @Override
    public String toString() {
        return "Student{" +
                "name='" + name + '\'' +
                ", stuNo=" + stuNo +
                '}';
    }

    @Override
    public boolean equals(Object o) {
        if (this == o) return true;
        if (!(o instanceof Student)) return false;
        Student student = (Student) o;
        return getStuNo() == student.getStuNo() && Objects.equals(getName(), student.getName());
    }

    @Override
    public int hashCode() {
        return Objects.hash(getName(), getStuNo());
    }

    @Override
    public int compareTo(Student o) {
        int n1=this.stuNo-o.getStuNo();
        return n1;
    }
}


Summary:

  1. When the HashMap was first created, the table was null. To save space, when the first element was added, the table capacity was adjusted to 16
  2. When the number of elements is greater than the threshold (16 * 0.75 = 12), the capacity will be expanded, and the size will be twice the original size. The purpose is to reduce and adjust the number of elements.
  3. jdk1.8 when the length of each linked list is greater than 8 and the number of elements is greater than or equal to 64, it will be adjusted to a red black tree in order to improve the execution efficiency
  4. jkd1.8 when the length of the linked list is less than 6, adjust it to a linked list
  5. jdk1. Before 8, the linked list was a header insertion, jdk1 8 followed by tail insertion.

TreeMap

Storage structure: red black tree

package com.xiang.map;

import java.util.Map;
import java.util.TreeMap;

/**
 * TreeMap Use of
 * Storage structure: red black tree
 */
public class TreeMap01 {
    public static void main(String[] args) {
        //Create collection
        TreeMap<Student,String> treeMap = new TreeMap<Student,String>();
        //1 add element
        Student s1=new Student("Sun WuKong",100);
        Student s2=new Student("Zhu Bajie",101);
        Student s3=new Student("Sha Wujing",102);
        treeMap.put(s1,"Beijing");
        treeMap.put(s2,"Shanghai");
        treeMap.put(s3,"Shenzhen");
        System.out.println("Number of elements:"+treeMap.size());
        System.out.println(treeMap.toString());

        //2 delete
//        treeMap.remove(s3);
//        System.out.println(treeMap.toString());

        //3 traversal
        //3.1 use keySet();
        System.out.println("======use keySet=========");
        for (Student key:treeMap.keySet()
             ) {
            System.out.println(key+treeMap.get(key));
        }
        //3.2 use entrySet();
        System.out.println("======use entrySet=========");
        for (Map.Entry<Student,String> entry: treeMap.entrySet()
             ) {
            System.out.println(entry.getKey()+entry.getValue());
        }

        //4 judgment
        System.out.println(treeMap.containsKey(new Student("Sun WuKong",100)));
        System.out.println(treeMap.isEmpty());
    }
}

Collections tool class

package com.xiang.collection;

import java.util.*;

/**
 * Collections Use of tool classes
 */
public class Collection03 {
    public static void main(String[] args) {
        List<Integer> list = new ArrayList<>();
        list.add(20);
        list.add(5);
        list.add(12);
        list.add(30);
        list.add(6);
        //Sort
        System.out.println("Before sorting:"+list.toString());
        Collections.sort(list);
        System.out.println("After sorting:"+list.toString());
        //Binary search Binary Search
        int i = Collections.binarySearch(list, 12);
        System.out.println(i);
        //Copy copy
        List<Integer> dest =new ArrayList<>();
        for (int j =0;j<list.size();j++){
            dest.add(0);
        }
        Collections.copy(dest,list);
        System.out.println(dest.toString());
        //Reverse reverse
        Collections.reverse(list);
        System.out.println("After reversal:"+list);

        //shuffle
        Collections.shuffle(list);
        System.out.println("After disruption:"+list);

        //Add: convert list to array
        System.out.println("======list Convert to array========");
        Integer[] arr = list.toArray(new Integer[0]);
        System.out.println(arr.length);
        System.out.println(Arrays.toString(arr));

        //Convert array to collection
        System.out.println("======Convert array to collection========");
        String[] names ={"Zhang San","Li Si","Wang Wu"};
        List<String> list2 = Arrays.asList(names);
        //Collection is a restricted collection and cannot be added or deleted
        System.out.println(list2);

        //When converting an array of basic types to a collection, you need to change it to a wrapper type
        Integer[] nums = {100,200,300,400,500};
        List<Integer> list3 = Arrays.asList(nums);
        System.out.println(list3);

    }
}

Collection summary

Keywords: Java

Added by camarosource on Wed, 15 Dec 2021 18:22:43 +0200