Beginners learn Java collection framework

  • 2021-10-24 23:11:33
  • OfStack

Directory Java Collection Framework Collection List Interface ArrayListVectorLinkedList: Generics: Set Interface HashSetTreeSetMap Interface Features: Traversal: HashMapHashtableTreeMap Summary

Java Collection Framework

Set

Concept: Container of objects, which defines common methods for operating on multiple objects. The function of array can be realized. Differences between collections and arrays: Array length is fixed, set length is not fixed Arrays can store primitive types and reference types, and collections can only store reference types.

Test


/*
            1. Add  2. Delete  3. Traversal  4. Judge 
         */
        Collection col = new ArrayList();
        col.add(" Zhang 3");
        col.add(" Li 4");
        col.add(" Wang 5");
//        col.add(" Zhang 3");
        System.out.println(col);
//        col.remove(" Zhang 3");
//        System.out.println(col);
        for (Object o : col) {
            System.out.println(o);
        }
        System.out.println("------------------");
        Iterator it = col.iterator();
        while (it.hasNext()){
            String next = (String) it.next();
            System.out.println(next);
        }
        System.out.println(col.isEmpty());
        System.out.println(col.contains(" Zhang 3"));

List interface

Features: Ordered, with subscripts, elements can be repeated.

You can add query elements at specified locations through corner markers.


 List list = new ArrayList();
        list.add("java");
        list.add("c++");
        list.add(1,"python");
        list.add(".net");
        System.out.println(list.size());
        System.out.println(list.toString());
        //1.for each Traversal 
        System.out.println("---------------");
        for (Object o : list) {
            System.out.println(o);
        }
        //2. Iterator traversal 
        System.out.println("---------------");
        Iterator iterator = list.iterator();
        while (iterator.hasNext()){
            System.out.println(iterator.next());
        }
        //3.list Iterator traversal 
        System.out.println("-------- Positive order -------");
        ListIterator listIterator = list.listIterator();
        while (listIterator.hasNext()){
            System.out.println(listIterator.next());
        }
        // You must traverse forward before reversing the order, so that the pointer points to the end of the list 1 Elements to develop traversal 
        System.out.println("-------- Reverse order -------");
        while (listIterator.hasPrevious()){
            System.out.println(listIterator.previousIndex() + ":" +listIterator.previous());
        }

When basic types of data such as numbers are added, automatic boxing will be performed.

Deleting numeric elements requires deleting by subscript, or converting the digits to the object class or the wrapper class corresponding to that type.

subList Returns 1 subset with header and no tail.

List Implementation Class

ArrayList

Array storage structure, fast query, slow addition and deletion; JDK version 1. 2 appears with fast running efficiency and unsafe threads. Source code analysis: DEFAULT_CAPACITY = 10 default capacity. Note: If no elements are added to the collection, the capacity is 0, and after adding 1 element, the capacity is 10. Each expansion is 1.5 times the original size. For example, when the 11th element is added, the capacity changes from 10 to 15. add () method source code: Why after adding 1 element, the capacity is 10.

public boolean add(E e) {
        ensureCapacityInternal(size + 1);  // Increments modCount!! Increase the number of modifications 
        elementData[size++] = e;
        return true;
    }
​private void ensureCapacityInternal(int minCapacity) {
        if (elementData == DEFAULTCAPACITY_EMPTY_ELEMENTDATA) {
            minCapacity = Math.max(DEFAULT_CAPACITY, minCapacity);
        }
​        ensureExplicitCapacity(minCapacity);
    }
​private void ensureExplicitCapacity(int minCapacity) {
        modCount++;
​
        // overflow-conscious code
        if (minCapacity - elementData.length > 0)
            grow(minCapacity);
    }
​private void grow(int minCapacity) {
        // overflow-conscious code
        int oldCapacity = elementData.length;
        int newCapacity = oldCapacity + (oldCapacity >> 1);
        if (newCapacity - minCapacity < 0)
            newCapacity = minCapacity;
        if (newCapacity - MAX_ARRAY_SIZE > 0)
            newCapacity = hugeCapacity(minCapacity);
        // minCapacity is usually close to size, so this is a win:
        elementData = Arrays.copyOf(elementData, newCapacity);
    }
elemetnData Array for holding elements size Actual Element Number

Test code:


 ArrayList arrayList = new ArrayList();
        Student s1 = new Student(" Zhang 3",18);
        Student s2 = new Student(" Li 4",18);
        Student s3 = new Student(" Wang 5",18);
        arrayList.add(s1);
        arrayList.add(s2);
        arrayList.add(s3);
        System.out.println(arrayList.toString());
        // Delete an element (need to override equals Method) 
        arrayList.remove(new Student(" Li 4",18));
        System.out.println(arrayList.size());
 public boolean equals(Object o) {
        if (this == o) return true;
        if (o == null || getClass() != o.getClass()) return false;
        Student student = (Student) o;
        return age == student.age && Objects.equals(name, student.name);
    }

Vector

Array storage structure, fast query, slow addition and deletion; JDK version 1.0 appears, which is slow and thread-safe. Enumerator traversal

Vector vector = new Vector();
        vector.add("java");
        vector.add("python");
        vector.add(".net");
        System.out.println(vector.toString());
        // Enumerator traversal 
        Enumeration elements = vector.elements();
        while (elements.hasMoreElements()){
            System.out.println(elements.nextElement());
        }

LinkedList:

Two-way linked list storage structure, fast addition and deletion, slow query.

Generics: A new feature introduced in JDK1.5, whose essence is to parameterize types and pass types as parameters; Common forms are generic classes, generic interfaces and generic methods. Benefits: Improve the reusability of code Prevent type conversion exceptions and improve code security

Generic collections: Parameterized, type-safe collections that force collection elements to be of type 1.

Features:

It can be checked at compile time, not thrown at run time. No type conversion is required when accessing. References between different generics cannot be assigned to each other, and there is no polymorphism in generics.

Set interface

Features: Unordered, no subscript, and non-repeatable elements

Methods: All inherited from the methods in Collection.

Set Implementation Class

HashSet

Storage structure: Hash table (array + linked list + red and black tree) Implementation of Element Non-duplication Based on HashCode Calculate the save location according to hashcode. If this location is empty, save it directly. If it is not empty, perform the next step. equals is called to confirm when the hash codes of the stored elements are the same, and if true is used, the latter is rejected. Otherwise, a linked list is generated.

public HashSet(){
  map = new HashMap<>();
}

Test code:


 HashSet<Student> set = new HashSet<>();
        Student s1 = new Student(" Zhang 3",18);
        Student s2 = new Student(" Li 4",18);
        Student s3 = new Student(" Wang 5",18);
        set.add(s1);
        set.add(s2);
        set.add(s3);
//        set.add(new Student(" Li 4",18));
        System.out.println(set.size());
        System.out.println(set.toString());
//        set.remove(new Student(" Li 4",18));
//        System.out.println(set.size());
//        System.out.println(set.toString());
        for (Student student : set) {
            System.out.println(student);
        }
        System.out.println("====================");
        Iterator<Student> iterator = set.iterator();
        while (iterator.hasNext()){
            System.out.println(iterator.next());
        }
public boolean equals(Object o) {
        if (this == o) return true;
        if (o == null || getClass() != o.getClass()) return false;
        Student student = (Student) o;
        return age == student.age && Objects.equals(name, student.name);
    }
​public int hashCode() {
        return Objects.hash(name, age);
    }

Reasons for adding 31 in hashcode override method

1.31 is a prime number to reduce hash collisions

2.31 Increased Efficiency of Implementation

TreeSet

Storage structure: red and black trees Realization of element non-repetition based on arrangement order The SortedSet interface is implemented, and the collection elements are automatically sorted The type of the element object must implement the Comparable interface, specifying the arrangement rule Determine whether it is a repeating element by CompareTo method

Test code: Using TreeSet collection to sort strings by length


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;
         }
        treeSet.add("zhangSan");
        treeSet.add("wkf");
        treeSet.add("asd");
        treeSet.add("abc");
        treeSet.add("ljCv");
        treeSet.add("liSi");
        treeSet.add("wanG");
​        System.out.println(treeSet.toString());
        System.out.println(treeSet.size());
​

Map interface

Features:

1. Used to store any key-value pair (Key, Value)

2. Key: Unordered, no subscript, no duplication allowed

3. Values: Unordered, no subscript, duplicate allowed

Traversal: keySet () method traverses: Gets the set set of key. entrySet () method traversal: Encapsulates map into a set of entry key-value pairs.

Test code:


Map<String, String> map = new HashMap<>();
        map.put("wkf","666");
        map.put("qwe","678");
        map.put("kfc","999");
        map.put("asd","694");
        Set<String> keySet = map.keySet();
        for (String s : keySet) {
            System.out.println(s + "=" + map.get(s));
        }
        System.out.println("===================");
        Set<Map.Entry<String, String>> entries = map.entrySet();
        for (Map.Entry<String, String> entry : entries) {
            System.out.println(entry.getKey() +"=" + entry.getValue() );
        }

HashMap

JDK version 1.2, the thread is unsafe and the running efficiency is fast; null is allowed as key or value. Construct an empty HashMap with a default initial capacity of 16 and a default load factor of 0.75. Load factor: For example, if the current collection capacity is 100, the expansion operation will be carried out when the data is stored in the 75th location. Source code analysis

static final int DEFAULT_INITIAL_CAPACITY = 1 << 4; // hashMap Initial capacity size 16
static final int MAXIMUM_CAPACITY = 1 << 30;//hashMap Maximum array capacity of 
static final float DEFAULT_LOAD_FACTOR = 0.75f;// Default load factor 
static final int TREEIFY_THRESHOLD = 8;//jdk1.8 Begin when the linked list length is greater than 8 When, adjust to red and black trees 
static final int UNTREEIFY_THRESHOLD = 6;//jdk1.8 Begin when the linked list length is less than 6 Adjust to a linked list when 
static final int MIN_TREEIFY_CAPACITY = 64;//jdk1.8 Begin when the linked list length is greater than 8 And the number of collection elements is greater than or equal to 64 Adjust to red and black trees when 
transient Node<K,V>[] table;// Arrays in a hash table 

Summary:

When HashMap was first created, table was null, and to save space, when the first element was added, the capacity of table was adjusted to 16 When the number of elements is greater than the threshold (16*0.75=12), expansion will be carried out, and the size after expansion will be twice that of the original. The purpose is to reduce the number of adjustment elements Starting from jdk1.8, when the length of linked list is greater than 8 and the number of set elements is greater than or equal to 64, it is adjusted to red-black tree to improve the execution efficiency jdk1.8, when the length of linked list is less than 6, adjust to linked list Before jdk1.8, the linked list is inserted at the head, and after jdk1.8, it is inserted at the tail

Hashtable

JDK version 1.0, thread-safe, slow running efficiency; null is not allowed as key or value Properties: A subclass of Hashtable that requires both key and value to be String and is typically used for reading configuration files.

TreeMap

Implement SortedMap interface (is the Map sub-interface), key can be automatically sorted.

Collections tool class

sort (): Ascending copy (): Replication binarySearch (): 2-point search Collections. binarySearch (list, the value to find); reverse (): Reverse shuffle (): Scrambling elements in a collection list to Array: list.toArray(new Integer[0]); Convert an array into a collection Arrays.asList(names); Collection is a restricted collection and cannot be added and

Summarize

This article is here, I hope to give you help, but also hope that you can pay more attention to this site more content!


Related articles: