java collection related knowledge

1, Concept of container

2, Container API

3, Collection interface

4, Iterator interface

5, Iterable interface

6, Set interface

7, Compatible interface

8, List interface

9, Map interface

-------------------------------------------------------------------------------------------------------------------------------------------------------------------------

1, Concept of container

Why use the collection framework?

If you don't know how many objects your program will need to run, or if you need to store objects in a more complex way -- you can use the java collection framework

 

 

2. Collection interface: stores a single value

Features:

1. Different types of data can be stored, while arrays can only store fixed types of data;

2. When the implementation of ArrayList subclass is used, the initialization length is 10. When the length is not enough, the capacity expansion operation will be performed automatically;

api method:

add: the parameter that must be passed in is the Object. Therefore, when writing the basic data type, the process of automatic boxing and automatic unpacking is included;

addAll: the elements of another collection in the field are in this collection;

 

clear: only the elements in the collection are cleared, but the collection object is not recycled;

remove: delete the specified element;

removeAll: delete the collection element;

 

Contains: determines whether the set contains the specified element value;

constainsAll: determine whether this set contains another set;

isEmpty: judge whether the set is empty;

Retain all: returns true if there are all elements of another collection in the collection, otherwise false;

Size: returns the size of the current set;

 

toArray: converts a collection to an array;

3, List and Set interfaces:

List features: orderly, not unique (repeatable)

What's the difference between ArrayList and LinkedList?

ArrayList is an array with variable length, which allocates continuous space in memory;

Advantages: high efficiency of traversal and random access elements;

Disadvantages: the efficiency of adding and deleting a large number of mobile elements is low, and the efficiency of querying by content is low;

LinkedList is a linked list storage method;

Advantages: high efficiency of adding and deleting;

Disadvantages: low efficiency of traversal and random access elements;

Vector: (often asked in interview)

1. Vector is also a subclass implementation of List interface;

2. Like ArrayList, the bottom layer of Vector is implemented by array;

3. Interview often asks the difference:

(1) ArrayList is thread unsafe and efficient, while Vector is thread safe and inefficient;

(2) when the ArrayList is expanded, it is 1.5 times of the capacity, and when the Vector is expanded, it is 2 times of the capacity;

Iterator: (need detailed supplement + source code analysis + Figure)

Circulation mode:

           do...while

           while

            for

There is also a way to enhance the for loop, which can simplify the writing of the loop

 1 package com.test.CollectionTest;
 2 
 3 import java.util.*;
 4 
 5 public class CollectionDemo {
 6     public static void main(String[] args) {
 7         Collection collection = new ArrayList();
 8         ((ArrayList) collection).add("abc");
 9         ((ArrayList) collection).add(123);
10         ((ArrayList) collection).add(true);
11 
12         for(int i=0;i<collection.size();i++){
13             System.out.println(((ArrayList) collection).get(i));
14         }
15         System.out.println("--------------------------------");
16         Iterator iterator = collection.iterator();
17         while(iterator.hasNext()){
18             System.out.println(iterator.next());
19         }
20         System.out.println("--------------------------------");
21         for(Object i : collection){
22             System.out.println(i);
23         }
24 
25     }
26 
27 }
CollectionDemo

 

All collection classes implement the Iterable interface by default, which means that they have the ability to enhance the for loop, that is, for each

Enhancing the for loop essentially uses the features of itertor

Methods:

                 iterator();

                 foreach();

In iterator's method, it is required to return an instance object of iterator's interface subclass, which contains hasNext() next() remove() (this method is not commonly used)

 

Difference between iterator and for loop: reference link: https://www.cnblogs.com/cloud-ken/p/11303084.html

In the process of iterating with iterator, if you delete one of the elements with list.remove, an error will be reported, concurrent modification exception (concurrent operation exception), so

If the traversal colleague needs to delete the element, listIterator() is recommended

ListIterator iterator provides forward and backward traversal

Always get the element value and downward traversal index through cursor and lastret pointer;

When forward traversal is used, the pointer must be at the end of the iterator, otherwise, the result value cannot be obtained

Detailed explanation: take ArrayList as an example

ArrayList.class code to implement the iteratable method (internal class implementation)

     

 

 

 1 . . . . . . 
 2 public Iterator<E> iterator() {
 3         return new Itr();
 4     }
 5 . . . . . . 
 6 private class Itr implements Iterator<E> {
 7         int cursor;       // index of next element to return
 8         int lastRet = -1; // index of last element returned; -1 if no such
 9         int expectedModCount = modCount;
10 
11         Itr() {}
12 
13         public boolean hasNext() {
14             return cursor != size;
15         }
16 
17         @SuppressWarnings("unchecked")
18         public E next() {
19             checkForComodification();
20             int i = cursor;
21             if (i >= size)
22                 throw new NoSuchElementException();
23             Object[] elementData = ArrayList.this.elementData;
24             if (i >= elementData.length)
25                 throw new ConcurrentModificationException();
26             cursor = i + 1;
27             return (E) elementData[lastRet = i];
28         }
29 
30         public void remove() {
31             if (lastRet < 0)
32                 throw new IllegalStateException();
33             checkForComodification();
34 
35             try {
36                 ArrayList.this.remove(lastRet);
37                 cursor = lastRet;
38                 lastRet = -1;
39                 expectedModCount = modCount;
40             } catch (IndexOutOfBoundsException ex) {
41                 throw new ConcurrentModificationException();
42             }
43         }
ArrayList

The remove method in iterator will reassign lastRet to cursor, lastRet=-1, so no ConcurrentModificationException error will occur.

Keywords: Java Mobile

Added by christa on Fri, 17 Apr 2020 14:20:33 +0300