Learning notes for java collection

Posted by hexguy on Fri, 31 Dec 2021 19:38:38 +0100

1 difference

1.1 array

Fixed length

You can store base and reference types

1.2 collection

The length is not fixed

Only reference types can be stored, and basic types can be boxed into reference types and saved into the collection through boxing operation.

Collection in Java util.* Bao Xia

2 Collection interface

2.1 introduction

ArrayList [key] [common]: array structure implementation, fast query, slow addition and deletion; JDK1.2 version, fast operation efficiency and unsafe thread.

Vector: array structure implementation, fast query, slow addition and deletion; JDK1.0 version, slow running efficiency and thread safety.

LinkedList: implementation of linked list structure, fast addition and deletion and slow query.

Fast addition and deletion: the head of the previous element points to the tail of the next element. When adding an element 3 between element 1 and element 2, only the tail of element 1 is changed from the head originally pointing to element 2 to the head of element 3, and the tail of element 3 points to the head of element 2. Similarly, to delete element 3 between element 1 and element 2, you only need to point the tail of element 1 to the head of element 2, and element 3 is recycled.

Slow query: find the address of the next element one by one through the index from the beginning to the end of the pointer

Methods provided by the Collection interface:

Boolean add (0object obj) / / add one object.

boolean addAll (Collection c) / / add all objects in a collection to this collection.

void clear() / / clear all objects in this collection.

boolean contains (Object o) / / check whether this collection contains o objects (call the indexOf method - first compare the passed o with the instantiated class for equals, and the two are true only if they have the same address in memory. If the passed o is a new class (xxx), it returns false because the addresses are different)

boolean equals (Object o) / / compare whether this collection is equal to the specified object.

boolean isEmpty() / / judge whether this collection is empty

boolean remove (0bject o) / / remove the O object from this collection (first call the equals method to determine whether the passed object and the object existing in the collection have the same address, return true and delete it, otherwise return false)

int size() / / returns the number of elements in this collection.

0bject[] toArray() / / convert this collection into an array.

wait

2.2 basic types of storage

CollectionTest.java

import java.util.*;

public class CollectionTest {
    public static void main(String[] args) {
        Collection c = new ArrayList();
        c.add("Zhang San");		//Add element
        c.add("Li Si");
        c.add("Wang Wu");
        System.out.println("Number of elements:"+c.size());
        System.out.println(c);  //Overriding toString method to call toString automatically

        c.remove("Zhang San");		//Delete element
        System.out.println(c);

        Collection co = new LinkedList();
        co.add("ZS");
        co.add("LS");
        co.add("WW");
        System.out.println(co);

        for (Object o : co) {	
            System.out.println(o);
        }
        for (Object o : c) {	//Traversal of a collection can only be an enhanced for loop
            System.out.println(o);
        }

        Iterator iterator = co.iterator();  //Iterator iterator
        while (iterator.hasNext()){
            String next = (String)iterator.next();
            System.out.println(next);
            iterator.remove();  //Use the remove of the iterator to delete. If you use collection Remove will report an error and modify the exception concurrently
        }
        System.out.println(co);
    }
}

result

The iterator iterator cannot use the original method of the Collection when traversing the Collection.

2.3 storage reference type

Student.java entity class

package jiheTest.collection;

public class Student {
    private String name;
    private int age;

    public Student() {
    }

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

    @Override
    public String toString() {
        return "Student{" +
                "name='" + name + '\'' +
                ", 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;
    }
}

CollectionTest2.java

import java.util.*;

public class CollectionTest2 {
    public static void main(String[] args) {
        Collection collection = new ArrayList();
        Student s1 = new Student("Zhang San",16);
        Student s2 = new Student("Li Si",12);
        Student s3 = new Student("Wang Wu",26);
        collection.add(s1);
        collection.add(s2);
        collection.add(s3);
        System.out.println(collection.toString());
        System.out.println(collection);
        System.out.println("-------enhance for---------");
        for (Object o : collection) {
            Student s = (Student)o ;
            System.out.println(s);
        }
        System.out.println("-------iterator  iterator---------");
        Iterator iterator = collection.iterator();
        while (iterator.hasNext()){
            System.out.println(iterator.next());
        }
    }
}

result

3 List interface

3.1 features

Ordered, subscript, element repeatable

3.2 method

void add(int index,Object o) / / Insert Object o at the index position. boolean addAll(int index,Collection c) / / add the elements in a collection to the index position in the collection. Object get(int index) / / returns the element at the specified position in the collection. List subList(int fromIndex,int toIndex) / / returns the collection elements between fromIndex and toIndex. Left closed right open section.

wait

3.3 traversal

import java.util.*;

public class ListTest {
    public static void main(String[] args) {
        List l = new ArrayList();
        l.add("A");
        l.add("B");
        l.add(0,"C");//Insert an element at subscript 0 and push the others one bit back
        System.out.println(l);
        System.out.println(l.get(1));//A
        System.out.println(l.subList(0,2));//C. A does not include subscript 2, i.e. B, closed left and open right.
        System.out.println("--------Can use ordinary for ergodic List-------");
        for (int i = 0; i < l.size(); i++) {       //The length of l is obtained by the size method
            System.out.println(l.get(i));   //Use the get method to pass parameter i to obtain the element corresponding to the subscript
        }
        System.out.println("---------You can also use enhanced for-----------");
        for (Object o : l) {
            System.out.println(o);
        }
        System.out.println("----------You can also use iterators----------");
        Iterator iterator = l.iterator();
        while (iterator.hasNext()){
            System.out.println(iterator.next());
        }
        System.out.println("========use List New method of interface Listiterator List iterator==============");
        ListIterator listIterator = l.listIterator();
        System.out.println("-----------hasNext-----------Traverse from front to back. After traversing, the pointer is at the last item in the list");
        while (listIterator.hasNext()){
            System.out.println(listIterator.nextIndex()+":"+listIterator.next());
        }
        System.out.println("-----------hasPrevious-------From back to front, move forward from the beginning of the pointer to the first item");
        while (listIterator.hasPrevious()){
            System.out.println(listIterator.previousIndex() + ":" + listIterator.previous());
        }
        System.out.println("indexOf Method to get the subscript of an element,element B Subscript of"+l.indexOf("B"));

    }
}

result:

3.4 adding and deleting basic types

import java.util.*;

public class ListTest2 {
    public static void main(String[] args) {
        List list = new ArrayList();
        list.add(10);   //At this point, the boxing operation is performed, and the basic type is encapsulated into a reference type for storage
        list.add(20);
        list.add(30);
        list.add(40);
        list.add(50);
        System.out.println(list);
//        System.out.println("---------list.remove(10) cannot directly delete the element '10', which specifies to delete the element with subscript 10 by default. If the list length is not enough, an error will be reported, and the subscript is out of range --------);
//        list.remove(10);
        System.out.println("-------Strong to Integer Object to delete--------");
        list.remove((Integer)10);
        System.out.println(list);
        System.out.println("-------Strong to Object Object to delete--------");
        list.remove((Object)20);
        System.out.println(list);
        System.out.println("------new One Integer Object to delete, which is equivalent to turning it into a reference type-------");
        list.remove(new Integer(30));
        System.out.println(list);
        System.out.println("---------use for Flashback traversal------------------");
        for (int i = list.size()-1; i >=0 ; i--) {
            System.out.println(list.get(i));
        }
    }
}

result

4 ArrayList (class implementing List interface)

Array structure implementation, fast query, slow addition and deletion; JDK1. Version 2, fast running efficiency and unsafe thread.

4.1 override the equals method in the entity class

Student.java:

public class Student {
    private String name;
    private int age;

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

    @Override
    public String toString() {
        return "Student{" +
                "name='" + name + '\'' +
                ", 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 the equals method************************************
    @Override
    public boolean equals(Object obj) {
        if(obj==this){
            return true;
        }
        if(obj==null){
            return false;
        }
        if(obj instanceof Student){
            if(((Student) obj).getName().equals(this.name)&&((Student) obj).getAge()==this.age){
                return true;
            }
        }
        return false;
    }
}

ArrayList.java:

import java.util.*;

public class ArrayListTest {
    public static void main(String[] args) {
        List list = new ArrayList();
        Student student = new Student("so-and-so",22);
        list.add(student);
        System.out.println(list);
        System.out.println("contain contains "+list.contains(new Student("so-and-so",22)));//false before overriding equals in Student class, true after overriding
        System.out.println("Query subscript indexOf"+list.indexOf(new Student("so-and-so",22)));
        System.out.println("delete remove"+list.remove(new Student("so-and-so",22)));
        System.out.println(list);
    }
}

result:

View the source code of ArrayList

indexOf method, remove method and lastIndexOf method are all useful to equals, and indexOf method is called in the contains method, so rewriting equals method will affect these methods, Originally, a new class () passed in the delete method remove returned false. After rewriting, the comparison is not to judge whether the object passed by equals and the entity class have the same address in memory, but to judge whether the field content of the object passed is the same as that of an object in the list.

4.2 part of source code analysis

ArrayList a = new ArrayList < > New when a collection object, the size is 0 and the capacity is 0;

When you call add to add an element, the capacity becomes 10 (constant default_capability). After 10, the capacity is expanded to 1.5 times of the original, that is, 15, 22, 33, 50, 75

In the source code, elementData is an array of elements.

5 Vector (class implementing List interface)

Array structure implementation, fast query, slow addition and deletion; JDK1.0 version, slow running efficiency and thread safety.

Not much is used for development now. Just understand it.

use

import java.util.*;

public class VectorTest {
    public static void main(String[] args) {
        Vector vector= new Vector<>();
//        increase
        vector.add("Zhang San");
        vector.add("Li Si");
        vector.add("Wang Wu");
//        Delete
/*        vector.remove(0);
        vector.remove("Wang Wu ");
        System.out.println(vector);
        vector.clear();
        System.out.println(vector);
*/
//      change
        vector.set(2, "so-and-so");
//      Search (traversal)
        System.out.println("--------use elements Method traversal--------");
        Enumeration elements = vector.elements();
        while (elements.hasMoreElements()){
            System.out.println(elements.nextElement());
        }
        System.out.println("--------Enhance with for loop-----------");
        for (Object o : vector) {
            System.out.println(o);
        }
        System.out.println("--------Use ordinary for loop-----------");
        for (int i = 0; i < vector.size(); i++) {
            System.out.println(vector.get(i));
        }
        System.out.println("============================");
        System.out.println("First element:"+vector.firstElement());
        System.out.println("Last element:"+vector.lastElement());
    }
}

result:

6 LinkedList (class implementing List interface)

(bidirectional) linked list structure, fast addition and deletion and slow query.

The method is basically the same as ArrayList

Unique methods:

Source code

void linkLast(E e) {
    final Node<E> l = last;
    final Node<E> newNode = new Node<>(l, e, null);
    last = newNode;
    if (l == null)
        first = newNode;
    else
        l.next = newNode;
    size++;
    modCount++;
}

  private static class Node<E> {
        E item;
        Node<E> next;
        Node<E> prev;

        Node(Node<E> prev, E element, Node<E> next) {
            this.item = element;
            this.next = next;
            this.prev = prev;
        }
    }

Different from ArrayList

(the picture is from "Qianfeng Java" of station B)

7 Set interface and HashSet implementation class

7.1 Set features

Elements are not repeated, traversal order: unordered.

7.2 HashSet set features

The underlying data structure is a hash table

The iterative order of the set is not guaranteed: the order of the stored and extracted elements is not guaranteed

There is no indexed method, so you can't use a normal for loop to traverse

Because it is a Set set, the HashSet Set set does not contain duplicate elements

7.3 source code process to ensure that elements are not repeated

Therefore, to ensure element uniqueness, you need to override hashCode and equals methods

7.4 rewrite the equals and hashCode methods

Override the equals and hashCode methods in the entity class:

In the entity class, alt+insert, select equals() and hashCode(), then go all the way to next, and finally finish directly

Rewritten student java:

public class Student {
    private String name;
    private int age;

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

    @Override
    public String toString() {
        return "Student{" +
                "name='" + name + '\'' +
                ", 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 boolean equals(Object o) {
        if (this == o) return true;
        if (o == null || getClass() != o.getClass()) return false;

        Student student = (Student) o;

        if (age != student.age) return false;
        return name != null ? name.equals(student.name) : student.name == null;
    }

    @Override
    public int hashCode() {
        int result = name != null ? name.hashCode() : 0;
        result = 31 * result + age;
        return result;
    }
}

The test adds two objects with the same property value

HashSetTest.java:

import java.util.HashSet;

public class HashSetTest {
    public static void main(String[] args) {
        HashSet<Student> hs = new HashSet<Student>();

        Student s1 = new Student("Zhang San", 18);
        Student s2 = new Student("Li Si", 19);
        Student s3 = new Student("Wang Wu", 20);
        Student s4 = new Student("Wang Wu", 20);  //After overriding the hashCode and equals methods in the Student class, objects with duplicate fields cannot be stored in the hashSet.
        hs.add(s1);
        hs.add(s2);
        hs.add(s3);
        hs.add(s4);
        System.out.println(hs);
    }
}

result:

[Student{name = 'Wang Wu', age=20}, Student{name = 'Zhang San', age=18}, Student{name = 'Li Si', age=19}]

7.5 hash table HashMap in data structure

Before jdk8, the bottom layer was implemented by array + linked list, which was an array with linked list elements

After jdk8, when the length is long, the bottom layer is optimized

The default initial length is 16

7.6 supplementary LinkedHashSet set

LinkedHashSet set features

The Set interface implemented by hash table and linked list has predictable iteration order

The order of elements is guaranteed by the linked list, that is, the storage and extraction order of elements are consistent

The hash table ensures that the elements are unique, that is, there are no duplicate elements

Figure from dark horse programmer

8 TreeSet collection overview

Figure from dark horse programmer

Natural sort Comparable

Is a parameterless construct of a TreeSet set

TreeSet<Student> ts = new TreeSet<Student>();

Student.java

public class Student implements Comparable<Student>{
//    The compareTo method rewritten when implementing Comparable is sorted by comparing the stored objects
//  When storing 1 item first and then the second item, compared with the first item, 0 is returned and not stored in the set. If greater than 0 is returned, it is stored in the back of the first item and less than 0 is stored in the front of the first item.
//  When the third element is stored, it is compared with the last element compared above, and the principle is the same.
    @Override
    public int compareTo(Student o) {
        return this.age-o.age==0?this.name.compareTo(o.name):this.age-o.age;    //The same age (the age difference between 2 objects is 0) returns the result of the comparison of the names and letters of 2 objects, otherwise it is sorted by the age difference. The String class overrides the compareTo method and sorts by letters
    }

    private String name;
    private int age;

    public Student() {
    }
    public Student(String name, int age) {
        this.name = name;
        this.age = age;
    }
    @Override
    public String toString() {
        return "Student{" +
                "name='" + name + '\'' +
                ", 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;
    }
}

TreeSetTest.java:

public class TreeSetTest {
    public static void main(String[] args) {
        TreeSet<Student> ts = new TreeSet<Student>();
        Student s1 = new Student("zhangsan", 18);
        Student s2 = new Student("lisi", 22);
        Student s3 = new Student("wangwu", 23);
        Student s4 = new Student("moumou", 19);
        Student s5 = new Student("abani", 18);  //Sort alphabetically at the same age
        Student s6 = new Student("abani", 18);  //Do not add duplicate elements
        ts.add(s1);
        ts.add(s2);
        ts.add(s3);
        ts.add(s4);
        ts.add(s5);
        ts.add(s6);
        for (Student t : ts) {
            System.out.println(t.getName() + ":" + t.getAge());
        }

    }
}

result:

abani:18
zhangsan:18
moumou:19
lisi:22
wangwu:23

Comparator

Parametric construction method of TreeSet

Using anonymous inner classes

TreeSet<Student> ts = new TreeSet<Student>(new Comparator<Student>() {
    @Override
    public int compare(Student o1, Student o2) {
        int num = o1.getAge() - o2.getAge();
        int num2 = num == 0 ? o1.getName().compareTo(o2.getName()) : num;
        return num2;
    }
});

TreeSet.java:

package jiheTest.collection;

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

public class TreeSetTest {
    public static void main(String[] args) {
        TreeSet<Student> ts = new TreeSet<Student>(new Comparator<Student>() {
            @Override
            public int compare(Student o1, Student o2) {
                int num = o1.getAge() - o2.getAge();
                int num2 = num == 0 ? o1.getName().compareTo(o2.getName()) : num;
                return num2;
            }
        });
        Student s1 = new Student("zhangsan", 18);
        Student s2 = new Student("lisi", 22);
        Student s3 = new Student("wangwu", 23);
        Student s4 = new Student("moumou", 19);
        Student s5 = new Student("abani", 18);  //Sort alphabetically at the same age
        Student s6 = new Student("abani", 18);  //Do not add duplicate elements
        ts.add(s1);
        ts.add(s2);
        ts.add(s3);
        ts.add(s4);
        ts.add(s5);
        ts.add(s6);
        for (Student t : ts) {
            System.out.println(t.getName() + ":" + t.getAge());
        }

    }
}

Student. There is no need to implement Comparable in Java

The operation results are the same as above.

Exercise: save 1-20 random numbers without repeating and traverse

code

import java.util.*;

public class RandomTest {
    public static void main(String[] args) {
        Set<Integer> set = new HashSet<Integer>();  //The generated random numbers are unordered
//        TreeSet<Integer> set = new TreeSet<>();   // The generated random numbers are sorted naturally

        Random random = new Random();
        while (set.size()<10){
            int num  = random.nextInt(20)+1;//Random number 0 ~ 19 + 1
            set.add(num);
        }

//        for (Integer integer : set) {
//            System.out.println(integer);
//        }
        Iterator<Integer> iterator = set.iterator();
        while (iterator.hasNext()){
            System.out.println(iterator.next());
        }

    }
}

The result is a chaotic number of 10 from 1 to 20

However, there is a problem. If the random number is changed from 1 to 10 and stored in the HashSet, the traversal results are ordered, because the HashSet is inserted with Integer, and its hashCode() implementation returns the int value itself. Therefore, the coincidental "sort by size" is introduced in the step of object hashCode.

JDK8 Java util. The hash algorithm in HashMap has a lower degree of confusion than JDK7; Through HashMap in the range of [0, 2 ^ 16-1] After hash (), you still get yourself.

The example falls into this range. In addition, there is no hash conflict in the HashMap in this example, which leads to the orderly insertion of elements into the open hash table of the HashMap in this example.

Therefore, adding 2 ^ 16 times before saving and subtracting 2 ^ 16 can be outside this range, and disorder can be realized. But this is the order each time it runs.

If it is a list ArrayList, you can use the method shuffle provided by Collections to pass in the list object and directly disrupt the sorting of the elements in the list.

9 generics

Dark horse programmer notes

  • Generic:

    It is a feature introduced in JDK5, which provides a compile time type security detection mechanism. This mechanism allows the detection of illegal types in compilation. Its essence is parameterized type, that is, the data type is specified as a parameter and refers to parameters. The most familiar thing is that there is a formal parameter when defining the method, and then the arguments are passed when the method is called. So what about parameterized types? As the name suggests, it is to parameterize the type from the original specific type, and then pass in the specific type when using / calling. This parameter type can be used in classes, methods and interfaces, which are called generic classes, generic methods and generic interfaces respectively

  • Generic definition format: < type >: Specifies the format of a type. The type here can be regarded as parameter < type 1, type 2. >: Specify mu lt iple types of formats separated by commas. The type here can be regarded as a formal parameter, and the given type can be regarded as an argument when calling in the future, and the type of the argument can only be a reference data type

  • The benefits of generics: advance run-time problems to compile time and avoid forced type conversion

9.1 generic classes

Generic entity class

GenericTest.java:

public class GenericTest<T> {	//Generic class
    private T t ;

    public T getT() {
        return t;
    }

    public void setT(T t) {
        this.t = t;
    }
    
    public T show(T t){
        return  t;
    }
}

GenericTest2.java:

public class GenericTest2 {
    public static void main(String[] args) {
        GenericTest<String> s1 = new GenericTest<String>();
        s1.setT("lqx");
        System.out.println(s1.getT());
        GenericTest<Integer> s2 = new GenericTest<Integer>();
        s2.setT(123);
        System.out.println(s2.getT());
        GenericTest<Boolean> s3 = new GenericTest<Boolean>();
        s3.setT(true);
        System.out.println(s3.getT());
        System.out.println("--------------------------");
        GenericTest<Boolean> s4 = new GenericTest<Boolean>();
        System.out.println(s4.show(false));
        GenericTest<Integer> s5 = new GenericTest<Integer>();
        System.out.println(s5.show(321));
        GenericTest<String> s6 = new GenericTest<String>();
        System.out.println(s6.show("lisi"));
        GenericTest<Double> s7 = new GenericTest<Double>();
        System.out.println(s7.show(0.0));
    }
}

result:

lqx
123
true
--------------------------
false
321
lisi
0.0

9.2 generic methods

GenericMethodTest.java:

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

GenericTest2.java:

public class GenericTest2 {
    public static void main(String[] args) {
        GenericMethodTest g1 = new GenericMethodTest();
        g1.show(true);
        g1.show(111);
        g1.show("wangwu");
        g1.show(1.2);
    }
}

result:

true
111
wangwu
1.2

9.3 type wildcards

9.4 use of variable length parameters

  • There is a static method in the Arrays tool class: public static List asList(T... a): returns a fixed size list supported by the specified array

    The returned collection cannot be added or deleted, but can be modified

  • There is a static method in the List interface: public static List of(E... elements): returns an immutable List containing any number of elements

    The returned collection cannot be added, deleted or modified

  • There is a static method in the Set interface: public static Set of(E...elements): returns an immutable Set containing any number of elements

    When giving elements, you cannot give duplicate elements

    The returned collection cannot be added or deleted. There is no modified method

10 Map

10.1 use

MapTest.java:

import java.util.*;

public class MapTest {
    public static void main(String[] args) {
        Map<Integer, String> map = new HashMap<Integer, String>();
        map.put(1,"zs");
        map.put(2,"ls");
        map.put(3,"ww");
        map.put(3,"zl");    //When k is the same, adding the latest value is equivalent to the update modification operation. HsahMap can ensure the uniqueness of key K, and the value V can be repeated.
        System.out.println(map);
    }
}

result

{1=zs, 2=ls, 3=zs}

10.2 common methods

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

Example code maptest java:

package jiheTest.collection;

import java.util.*;

public class MapTest {
    public static void main(String[] args) {
        Map<Integer, String> map = new HashMap<Integer, String>();
        map.put(1,"zs");
        map.put(2,"ls");
        map.put(3,"ww");

        Set<Integer> keySet = map.keySet();
        for (Integer key : keySet) {
            System.out.println(key);
            System.out.println(map.get(key));
        }

        Set<Map.Entry<Integer, String>> entries = map.entrySet();
        System.out.println(entries);
        for (Map.Entry<Integer, String> entry : entries) {
            System.out.println(entry.getKey()+":"+entry.getValue());
        }

    }
}

result:

1
zs
2
ls
3
ww
[1=zs, 2=ls, 3=ww]
1:zs
2:ls
3:ww

10.3 ArrayList embedded HashMap

It can also be said that the ArrayList is embedded with HashMap. This data type is somewhat similar to the list [{object}, {object}...] in JavaScript Data, front-end JSON data.

ArrayListAndHashMap.java:

import java.util.*;

public class ArrayListAndHashMap {
    public static void main(String[] args) {
        ArrayList<HashMap<String, String>> arrayList = new ArrayList<>();
        HashMap<String, String> hm1 = new HashMap<>();
        hm1.put("Sharpshooter","Launcher ");
        hm1.put("swordman ","Asura");
        arrayList.add(hm1);

        HashMap<String, String> hm2 = new HashMap<>();
        hm2.put("Gladiator","qigong practitioner");
        hm2.put("magician","Element division");
        arrayList.add(hm2);

        HashMap<String, String> hm3 = new HashMap<>();
        hm3.put("Clergy","Exorcist ");
        hm3.put("Night messenger","assassin");
        arrayList.add(hm3);

        System.out.println(arrayList);
        
        for (HashMap<String, String> hashMaps : arrayList) {
            Set<Map.Entry<String, String>> hashMap = hashMaps.entrySet();
            for (Map.Entry<String, String> hm : hashMap) {
                System.out.println(hm.getKey()+"--Transfer-->"+hm.getValue());
            }
        }
    }
}

result:

[{swordman =Asura, Sharpshooter=Launcher }, {magician=Element division, Gladiator=qigong practitioner}, {Night messenger=assassin, Clergy=Exorcist }]
swordman --Transfer-->Asura
 Sharpshooter--Transfer-->Launcher 
magician--Transfer-->Element division
 Gladiator--Transfer-->qigong practitioner
 Night messenger--Transfer-->assassin
 Clergy--Transfer-->Exorcist 

10.4 embedded ArrayList in HashMap

HashMapAndArrayList.java:

import java.util.*;

public class HashMapAndArrayList {
    public static void main(String[] args) {
        HashMap<String, ArrayList<String>> hashMap = new HashMap<>();
        ArrayList<String> gjs = new ArrayList<>();
        gjs.add("Sword soul");
        gjs.add("Ghost cry");
        hashMap.put("swordman ",gjs);

        ArrayList<String> gdj = new ArrayList<>();
        gdj.add("qigong practitioner");
        gdj.add("Grappler ");
        hashMap.put("Gladiator",gdj);

        ArrayList<String> sqs = new ArrayList<>();
        sqs.add("Ammunition expert");
        sqs.add("Roaming gunman");
        hashMap.put("Sharpshooter",sqs);

        Set<Map.Entry<String, ArrayList<String>>> entries = hashMap.entrySet();
        for (Map.Entry<String, ArrayList<String>> entry : entries) {
            System.out.print(entry.getKey()+"Including occupation:");
            for (String s : entry.getValue()) {
                System.out.print(" "+s);
            }
            System.out.println();
        }
    }
}

result:

Ghost swordsman includes profession: Sword ghost ghost sobbing
 Gladiators include occupations: Qigong master, judo master
 Sharpshooter includes classes: ammunition expert, roaming gunner

In addition, TreeMap is a sort Map, similar to TreeSet

11 continuous update...

Topics: Java Back-end