Java19 -- Collection 1 (Collection+List+ArrayList+LinkedList)

Keywords: Java list

1 Collection interface

1.1 general

The English name Collection is the data structure used to store objects. The length is variable, and different types of objects can be stored in the Collection. It also provides a set of methods to operate batch objects.

Disadvantages of array: the length is fixed, the access mode is single, and the operations such as insertion and deletion are cumbersome.

1.2 inheritance structure of sets

Collection Interface

-- List Interface: the data is orderly and can be repeated.

   -- ArrayList Subclass

   -- LinkedList Subclass

-- Set Interface: the data is out of order, and duplicate values cannot be saved

   -- HashSet Subclass

-- Map Interface: key value pair storage data

-- HashMap

Collections Tool class

1.3 common methods

boolean add(E e): Add element.

boolean addAll(Collection  c): Add a small set to a large set.

boolean contains(Object o) :  If this collection Contains the specified element, returns true. 

boolean isEmpty() : If this collection If there is no element, return true. 

Iterator<E> iterator(): Return here collection Iterator that iterates over the element of.

boolean remove(Object o) : from then on collection Removes a single instance of the specified element from the.

int size() : Return to this collection Number of elements in the.

Objec[] toArray(): Returns an array of objects

1.4 exercise 1: Common test methods

package seday11;

import java.util.ArrayList;

import java.util.Collection;

import java.util.Iterator;

public class Test_301_Collection {

       public static void main(String[] args) {

              Collection c = new ArrayList();//Interface cannot create object directly

              c.add("hello");//Add element

              c.add("java");//Add element

              c.add("~");//Add element

              c.add(10);//After jdk5, there is an automatic packing function, which is equivalent to packing 10 Integer.valueOf(10)

              System.out.println(c.remove("~"));//Removing Elements 

              System.out.println(c.contains("a"));//Judgment inclusion relationship

              System.out.println(c.size());//Length of collection



              //for traversal set

              for(int i =0 ;i<c.size();i++) {



              //Iterator iterator traversal

              Iterator it = c.iterator();//Iterator that iterates over the collection

              while (it.hasNext()) {//Returns true if there are still elements

                     System.out.println(;//Returns the next element obtained by the iteration

              }   } }

2 List interface

2.1 general

An ordered collection (also known as a sequence). Users of this interface can precisely control the insertion position of each element in the list. Users can access an element based on its integer index (position in the list) and search for elements in the list.

2.2 features

1. Data order

2. Allow duplicate elements to be stored

3. Every element has an index

2.3 common methods

ListIterator<E> listIterator()

          Returns the list iterator (in the appropriate order) for this list element.

 ListIterator<E> listIterator(int index)

          Returns the list iterator (in the appropriate order) of the elements in the list, starting at the specified position in the list.

 void add(int index, E element)

          Inserts the specified element at the specified position in the list (optional operation).

 boolean addAll(int index, Collection<? extends E> c)

          Will specify collection All elements in the are inserted at the specified location in the list (optional).

 List<E> subList(int fromIndex, int toIndex)

     Returns the specified in the list fromIndex(Including) and toIndex(Partial views between (not included).

E get(int index)

          Returns the element at the specified location in the list.  

int indexOf(Object o)

          Returns the index of the specified element that appears for the first time in this list; If this list does not contain the element, returns -1. 

2.4 exercise 1: test common methods

Create day12 project

Create cn.tedu.list package


package cn.tedu.list;


import java.util.ArrayList;

import java.util.Iterator;

import java.util.List;

import java.util.ListIterator;


//This is a common method used to test the List interface

public class Test1_List {


    public static void main(String[] args) {

       //1. Create List object

       //Feature 1: List collection elements have indexes, which can directly locate elements according to the indexes

       List list = new ArrayList();


       //2. Common methods








       list.add(3,666);//Adds the specified element at the index of 3


       //Feature 2: the elements are orderly and can be placed as they are stored

       System.out.println(list);//[111, 222, 333, 666, 444, a, abc]


       Object obj = list.get(4);//get(m)-m is the index value to get the element at the specified index position




       //3. Iterates / traverses the elements in the collection

       //Use the iterator() provided by the Collection interface

       Iterator it = list.iterator();

       while(it.hasNext()) {//Determine whether there is the next element in the set

           Object o =;

//         System.out.println(o);


       //Use listIterator() provided by the List interface

       //interfaceListIterator extends Iterator

       //Difference: you can use the functions of the parent interface and have your own unique functions. You can not only iterate backward, but also reverse

       ListIterator it2 = list.listIterator();

       while(it2.hasNext()) {

           Object o =;

//         System.out.println(o);



       List list2 = list.subList(1, 3);//subList(m,n)-m is the start index and N is the end index, including header and no tail, similar to String.subString(m,n)



3 ArrayList

3.1 general

  1. Exist in java.util In the bag.
  2. The internal data is stored in an array, which encapsulates the operation of the array, and each object has a subscript.
  3. The default initial capacity of the internal array is 10. If it is not enough, it will be 1.5 Double capacity growth.
  4. Query is fast, and the efficiency of adding and deleting data will be reduced.

3.2 creating objects

new ArrayList(): The initial capacity is 10

3.3 exercise 1: Common test methods

Common API s, including subscript traversal and iterator traversal

package seday11;

import java.util.ArrayList;

public class Test3_AL {

       public static void main(String[] args) {

              ArrayList list = new ArrayList();

              list.add("aaa");//Store data




              System.out.println(list);//Contents in list

              System.out.println(list.size());//Set length

              System.out.println(list.get(1));//Get element by subscript



              System.out.println(list.remove(2));//Remove the element corresponding to the subscript



                     //Subscript traversal

                     for (int i = 0; i < list.size(); i++) {




       //Iterator iterates, encapsulating subscripts

                     Iterator<String> it = list.iterator();

                     while (it.hasNext()) {//If there is data

                            String s =;//Traverse backward one by one





4 LinkedList

4.1 General

Two way linked list, high efficiency at both ends. The bottom layer is the implementation of array and linked list.

4.2 common methods







addFirst()  addLast()

getFirst()  getLast()

removeFirst()  removeLast()

4.3 exercise 1: testing iterator traversal

Bidirectional linked list: low efficiency of subscript traversal and high efficiency of iterator traversal

package dd;


import java.util.ArrayList;

import java.util.Iterator;

import java.util.LinkedList;


public class tt {

       public static void main(String[] args) throws Exception {

              LinkedList ll = new LinkedList ();

              for (int i = 0; i < 100000; i++) {







       private static void f2(LinkedList<Integer> ll) {

              long t = System.currentTimeMillis();

              Iterator it = ll.iterator();

              while(it.hasNext()) {



              t = System.currentTimeMillis()-t;




       private static void f1(LinkedList<Integer> ll) {

              long t = System.currentTimeMillis();

              for (int i = 0; i < ll.size(); i++) {



              long t1 = System.currentTimeMillis();




5 expansion

5.1 ArrayList expansion

ArrayList is equivalent to delaying the allocation of object array space when initialCapacity is not specified. Only 10 (default) object spaces are allocated when the element is inserted for the first time. If 20 data need to be added, the capacity of ArrayList will be changed to 10 for the first time (as shown in Figure 1 below); After that, the capacity expansion will increase by 1.5 times. That is, when the 11th data is added, the ArrayList continues to expand to 10 * 1.5 = 15 (as shown in Figure 2 below); When the 16th data is added, continue to expand to 15 * 1.5 = 22

ArrayList does not expose the number of its capacity. Looking at the source code, we can know that the actual value is stored in the elementData object array. Then we only need to get the length of the array and observe how many times its value has changed to know how many times its capacity has been expanded. How to get it? Only reflection technology can be used.

5.2 HashMap expansion

Growth factor:

static final float DEFAULT_LOAD_FACTOR = 0.75f;

The previous description has found that when your space is only 10, it is easy to cause the address corresponding to the hashcode of two objects to be one location. This will cause two objects to form a hash bucket (linked list). At this time, there is a parameter of loading factor. The default value is 0.75. If you have 100 hashmap space, the hashmap needs to be expanded when you insert 75 elements. Otherwise, a long hash bucket structure will be formed, and the time will be increased for query and insertion, because it needs to compare equals one by one. But you can't make the loading factor very small, such as 0.01, which is obviously inappropriate. Frequent capacity expansion will greatly consume your memory. At this time, there is a balance. The default value in jdk is 0.75. Of course, the load factor can be adjusted according to your actual situation.

Posted by robocop on Wed, 27 Oct 2021 19:26:22 -0700