What are the characteristics of the List collection in Java? (with video tutorial)

This article will give you a detailed explanation of the List collection in Java. This is a knowledge point that we often use when developing, and it is also a very important knowledge point for everyone to learn Java. It is also something we may ask during interviews. question.

The article is long and full of dry goods. It is recommended that you bookmark and learn slowly. At the end of the article, there is a key summary of this article, and the homepage has a full series of articles to share. For technical issues, welcome to communicate and discuss with us!

foreword

In the last article, I introduced collections in Java to you. We learned about the origin, characteristics, and some interface APIs of collections, but these contents are all focused on theory. So starting from today's article, we will learn the List collection from a practical perspective. It can be said that the List collection is the most used collection during development, especially the ArrayList is often used.

So for today's content, I hope you will read and practice well

The full text is about [5800] words, no nonsense, just pure dry goods that allow you to learn techniques and understand principles! This article has a wealth of cases and videos with pictures, so that you can better understand and use the technical concepts in the article, and can bring you enough enlightening thinking...

1. Introduction to List Collection

1 Overview

List itself is an interface, which inherits from the Collection interface, and it has two commonly used implementation subclasses, ArrayList and LinkedList. From the perspective of functional characteristics, List is an ordered and repeatable single-column collection. Each element in the collection has a corresponding sequential index , and we can use this index to access the collection elements at the specified position. By default, List will index elements in the order in which they are added. The index of the first element added to the List collection is 0, the second is 1, and so on. So the behavior of List is almost exactly the same as that of array, they are both ordered storage structures. In addition, repeated elements are allowed in the List collection, and there can even be multiple null values .

But if we use arrays to add and delete elements, it will be very inconvenient. For example, to delete the element with index 2 from an existing array {'A', 'B', 'C', 'D', 'E'}, this "delete" operation actually removes the element after 'C' The elements move forward one position in turn; and the "add" operation actually moves the elements after the specified position back one position in order to make room for the newly added element. For both operations, it would be very cumbersome to implement using arrays. So in practical applications, when we add or delete elements, we generally use ordered lists (such as ArrayList) instead of arrays.

2. Class relationship

Let's take a look at the class relationship of the List interface, as shown in the following figure:

image.png

From this class relationship, we can see that the List interface inherits the Collection interface and has ArrayList、LinkedList、Vectorother subclasses. Among them, Vector is not very commonly used now, so we focus on mastering ArrayListand summing.LinkedList

3. Commonly used API methods

Some common methods of subclasses are defined in the List interface, as follows:

  • boolean add(E e) : Add a data element at the end of the collection;
  • boolean add(int index, E e) : Add a data element at the specified index of the collection;
  • E remove(int index) : delete the element at the specified index in the collection;
  • boolean remove(Object e) : delete an element in the collection;
  • E get(int index) : Get the element at the specified index in the collection;
  • int size() : Get the size of the collection (including the number of elements).

The above methods are some of the more commonly used methods when we develop, we must remember

4. List object creation method

As List is an interface, we usually cannot create its objects directly with new List. Java provides us with the following two ways to create List objects:

  • Created by polymorphism : a subclass of new List, such as new ArrayList(), etc.;
  • Created by the List.of() method : the of() method can quickly create a List object based on the given data elements, but this method does not accept null values. If null is passed in, a NullPointerException will be thrown.
import java.util.ArrayList;
import java.util.LinkedList;
import java.util.List;

public class Demo01 {
    
    
	public static void main(String[] args) {
    
    
		//创建List对象方式一:
		List<String> list1=new ArrayList<>();
		
		List<String> list2=new LinkedList<>();
		
		//创建List对象方式二:
		List<Integer> list3 = List.of(1,3,5,7,9);

    	//该方式不能传入null参数,否则会产生NullPointerException异常
		//List<Integer> list4 = List.of(1,3,5,7,9,null);
	}
}

5. List collection traversal method

Many times, we will perform traversal operations on collections, that is, to take out each element in the collection one by one. The following are several commonly used collection traversal methods:

  • Ordinary for loop with get (index value) method for traversal: the code for this traversal method is more complicated to implement, and the get (int) value method is only more efficient for ArrayList, but less efficient for LinkedList, and the access speed is larger when the index is larger slower.
  • Enhanced for loop for traversal: We can also use enhanced for loop for traversal, which is more concise than ordinary for loop.
  • Use the Iterator iterator for collection traversal: when different List objects call the iterator() method, it will return Iterator objects of different implementations, and the Iterator object always has the highest access efficiency for the collection.
import java.util.Iterator;
import java.util.List;

public class Demo02 {
    
    
	public static void main(String[] args) {
    
    
		//List遍历方式一,普通for循环:
		List<String> list = List.of("java", "大数据", "壹壹哥");
		for(int i=0;i<list.size();i++) {
    
    
			System.out.println("遍历方式一,值="+list.get(i));
		}
		
		//List遍历方式二,迭代器:
		Iterator<String> it = list.iterator();
        while(it.hasNext()){
    
    
        	//取出下一个值
            String value = it.next();
            System.out.println("遍历方式二,值="+value);
        }

        //List遍历方式三,增强for循环:内部会自动使用Iterator
		for(String item:list) {
    
    
			System.out.println("遍历方式三,item="+item);
		}
	}
}

The Iterator object mentioned above has two common methods, as follows:

boolean hasNext(): This method is used to determine whether there is another element in the collection;
E next(): This method is used to return the next element of the collection.

Although the code for using Iterator to traverse the List collection looks more complicated than using indexes, the efficiency of Iterator to traverse the List collection is the most efficient way.

In addition, as long as it is a collection class that implements the Iterable interface, we can directly use the for each enhanced loop to traverse. In the enhanced for loop, the Java compiler will automatically turn the for each loop into an Iterator-based traversal method.

6. List and array conversion method

In fact, List and Array are similar in many places. For example, they can perform operations such as traversing and fetching data elements according to the index. Because of this similarity, it is possible to convert between List and array, that is, the List collection can be converted into an array, and the array can also be converted into a List collection.

6.1 List to array

In general, there are several ways to convert List to array as follows:

  • toArray() method : This method will return an Object[] array, but this method will lose type information and is rarely used in actual development;
  • toArray(T[]) method : Pass in an Array of the same type as the data element of the collection, and List will automatically copy the elements to the incoming Array;
  • T[] toArray(IntFunction<T[]> generator) method : functional writing, this is a new feature in Java, we will explain it separately later. Everyone can continue to pay attention
import java.util.List;

public class Demo03 {
    
    
	public static void main(String[] args) {
    
    
		List<String> list = List.of("java", "大数据", "壹壹哥");
		
		// List转数组方式一:返回一个Object[]数组
		Object[] array = list.toArray();
        for (Object val : array) {
    
    
            System.out.println("方式一,value="+val);
        }
        
        // List转数组方式二,给toArray(T[])传入与数组元素类型相同的Array,如果数组类型与集合数据元素类型不匹配则会产生如下异常:
        // java.lang.ArrayStoreException: arraycopy: element type mismatch: 
        //can not cast one of the elements of java.lang.Object[] to the type of the destination array, java.lang.Integer
        String[] array2 = list.toArray(new String[list.size()]);
        for (String val : array2) {
    
    
            System.out.println("方式二,value="+val);
        }
        
        // List转数组方式三:返回一个String[]数组
        String[] array3 = list.toArray(String[]::new);
        for (String val : array3) {
    
    
            System.out.println("方式二,value="+val);
        }
	}
}

In this case, the first implementation is to call the toArray() method to directly return an Object[] array, but this method will lose type information, so development is rarely used.

The second way is to pass an Array of the same type as the collection data element to the toArray(T[]) method, and the List will automatically copy the elements to the passed Array array. If the Array type does not match the data element type of the collection, "java.lang. ArrayStoreException : arraycopy: element type mismatch : can not cast one of the elements of java.lang.Object[] to the type of the destination array …"abnormal.

The third way is through the T[] toArray(IntFunction<T[]> generator) method defined by the List interface. This is a functional writing method, and I will explain it to you separately later. You can continue to follow us

6.2 Array to List

Conversely, an array can also be converted into a List collection. The general method is as follows:

  • List.of(T...) method : This method will return a read-only List collection. If we call the add() and remove() methods on the read-only List, an UnsupportedOperationException will be thrown. Among them, T is a generic parameter, representing the array to be converted into a List collection;
  • Arrays.asList(T...) method : This method will also return a List collection, but the List it returns is not necessarily ArrayList or LinkedList, because List is just an interface.
import java.util.Arrays;
import java.util.List;

public class Demo04 {
    
    
	public static void main(String[] args) {
    
    
		// 数组转List的方式一:List.of()返回一个只读的集合,不能进行add/remove等修改操作。
		List<Integer> values = List.of(1,8,222,10,5);
        for (Integer val : values) {
    
    
            System.out.println("方式一,value="+val);
            
            //该集合是一种只读的集合,不能在遍历时进行增删改等更新操作,只能进行读取操作,
            //否则会产生java.lang.UnsupportedOperationException异常
            //values.remove(0);
        }
        
        // 数组转List的方式二:Arrays.asList()返回一个只读的集合,不能进行add/remove等修改操作。
        List<String> items = Arrays.asList("java","壹壹哥","元宇宙");
        for (String item : items) {
    
    
            System.out.println("方式二,value="+item);
            
            //不可以进行增删改操作
            //items.add("sss");
            //items.remove(0);
        }
	}
}

In this case, whether we use the List.of() method or the Arrays.asList() method, only a read-only collection will be returned. This kind of collection cannot perform update operations such as addition, deletion, modification, etc. during traversal, and can only perform read operations, otherwise java.lang.UnsupportedOperationException will be generated .

Two. ArrayList collection

1 Introduction

ArrayList is an array queue located in the java.util package, which inherits from AbstractList and implements the List interface. The underlying layer is an array that can be dynamically modified . The difference between this array and ordinary arrays is that it has no fixed size limit, and we can dynamically add or delete elements to it.

image.png

The data stored in the collection is called "element", and we can use the index to access each element in the collection. In order to facilitate our operation of these elements, ArrayList provides us with related functions such as adding, deleting, modifying, and traversing.

Because the bottom layer of ArrayList is a dynamic array, this collection is suitable for fast random access to elements (traversal query). In addition, the addition and deletion of tail members is also faster, but the insertion and deletion of elements at other positions are relatively slow. slow . Based on this feature, ArrayList has the characteristics of fast query and slow addition and deletion .

2. Common methods

ArrayList provides us with the following methods, we can first understand:

method describe
add() Insert data elements into the specified position of ArrayList
addAll() Add all elements in a new collection to ArrayList
clear() Delete all elements in ArrayList
contains() Determine whether the element is in the ArrayList
get() Get elements in ArrayList by index value
indexOf() Returns the index value of an element in the ArrayList
removeAll() Delete all elements of the specified collection in the ArrayList
remove() Delete a single element in ArrayList
size() Returns the number of elements in the ArrayList
isEmpty() Determine whether the ArrayList is empty
subList() Intercept some elements of ArrayList
set() Replaces the element at the specified index in the ArrayList
sort() Sort the data elements of ArrayList
toArray() Convert ArrayList to Array
toString() Convert ArrayList to String
ensureCapacity() Set the ArrayList with the specified capacity
lastIndexOf() Returns the position of the last occurrence of the specified element in the ArrayList
retainAll() preserves the data elements in the specified collection
containsAll() Check whether the ArrayList contains all the elements of the specified collection
trimToSize() Adjust the capacity of ArrayList to the number of elements in the array
removeRange() Delete the elements existing between the specified indexes in the ArrayList
replaceAll() Replaces each element in the specified array with the given data element
removeIf() Remove all ArrayList elements that meet certain criteria
forEach() Traverse each element in the ArrayList and perform specific operations

Next, we will select a few commonly used methods, and explain ArrayListtheir usage through a few cases.

3. Add elements

ArrayList provides us with a number of methods related to addition, such as add() and addAll() methods, which can add elements to the collection. In addition, if we want to calculate the number of elements in the ArrayList, we can use the size() method.

import java.util.ArrayList;

public class Demo05 {
    
    
	public static void main(String[] args) {
    
    
		//创建ArrayList集合,<String>中的是泛型,后面我们会专门讲解泛型
		ArrayList<String> names = new ArrayList<String>();
		//一个一个地添加元素
		names.add("一一哥");
		names.add("java");
		names.add("数学");
        
		//遍历集合
        for (String name : names) {
    
    
            System.out.println("name="+name+",size="+names.size());
        }
        
        ArrayList<String> names2 = new ArrayList<String>();
        names2.add("壹壹哥");
        //在A集合中追加B集合
        names2.addAll(names);
        
        //遍历集合
        for (String name : names2) {
    
    
            System.out.println("name="+name);
        }
	}
}

In the above code, this part is generic, which will be explained to you later, so stay tuned.

4. Traversing elements

The way we traverse the elements in the ArrayList is actually the same as the traversal of the List. We can use ordinary for loops, enhanced for loops, Iterator iterators, etc. to traverse the collection. Here we will not show its usage separately. .

5. Modify elements

After we use the add() method to add elements to the collection, if we want to modify the elements in the collection, we can use the set() method.

import java.util.ArrayList;

public class Demo06 {
    
    
	public static void main(String[] args) {
    
    
		//创建ArrayList集合,<String>中的是泛型,后面我们会专门讲解泛型
		ArrayList<String> names = new ArrayList<String>();
		//一个一个地添加元素
		names.add("一一哥");
		names.add("java");
		names.add("数学");
		
		//修改集合中的元素:第一个参数是集合中的索引,第二个是要修改的值
		names.set(1, "Android"); 
		names.set(2, "iOS"); 
        
		//遍历集合
        for (String name : names) {
    
    
            System.out.println("name="+name);
        }
	}
}

6. Delete elements

If we want to delete the elements in the ArrayList, we can use remove()、removeAll()the etc method.

import java.util.ArrayList;

public class Demo07 {
    
    
	public static void main(String[] args) {
    
    
		//创建ArrayList集合,<String>中的是泛型,后面我们会专门讲解泛型
		ArrayList<String> names = new ArrayList<String>();
		//一个一个地添加元素
		names.add("一一哥");
		names.add("java");
		names.add("数学");
		
		//删除集合中指定位置上的某个元素
		names.remove(0);
		//删除集合中的某个指定元素
		names.remove("java");
        
		//遍历集合
        for (String name : names) {
    
    
            System.out.println("name="+name);
        }
        
        ArrayList<String> names2 = new ArrayList<String>();
        names2.add("语文");
		names2.add("英语");
		names2.add("数学");
		//删除本集合中的另一个集合
        names2.removeAll(names);
        //遍历集合
        for (String name : names2) {
    
    
            System.out.println("name2="+name);
        }
	}
}

7. Collection sorting

We can sort the collection in ascending order using the Collections.sort() method.

import java.util.ArrayList;
import java.util.Collections;

public class Demo08 {
    
    

	public static void main(String[] args) {
    
    
		//创建ArrayList集合
		ArrayList<Integer> nums = new ArrayList<>();
		//一个一个地添加元素
		nums.add(100);
		nums.add(85);
		nums.add(120);
		nums.add(55);
		
		//对集合进行排序,默认是升序排列
		Collections.sort(nums);  
        
		//遍历集合
        for (Integer num : nums) {
    
    
            System.out.println("num="+num);
        }
	}
}

8. Companion Video

The supporting video link for this section is as follows : click the link to view

3. LinkedList collection

1 Introduction

LinkedListThe linked list structure is used to save data, so it is a linked list collection, similar to ArrayList, and also a subclass of List, located in the java.util package. Its underlying layer is based on a common data structure such as a linear linked list, but it does not store data in a linear order, but stores the address of the next node in each node.

image.png

The advantage of LinkedList is that it is convenient to insert or delete elements into the collection , especially when elements need to be frequently inserted and deleted from the collection, using the LinkedList class is more efficient than ArrayList. However, the speed of random access to elements in LinkedList is relatively slow, that is, the speed of retrieving elements at specific index positions in the collection is slow.

2. LinkedList class relationship

LinkedListDirectly inherited from AbstractSequentialListand implements multiple interfaces such as List, Deque, Cloneable, and Serializable. By implementing the List interface, it has the ability to operate lists; by implementing the Cloneable interface, it has the ability to clone; by implementing the Queue and Deque interfaces, it can be used as a queue; by implementing the Serializable interface, it can have serialization capabilities. The LinkedList class structure relationship is shown in the following figure:

image.png

3. LinkedList vs ArrayList

Compared with ArrayList, LinkedList is more efficient for adding and deleting operations, but less efficient for searching and modifying operations . Based on this feature, we can use ArrayList in the following situations:

  • It is necessary to frequently access an element in the list;
  • It is only necessary to add and remove an element at the end of the list .

When encountering the following situations, you can consider using LinkedList:

  • Some elements in the list need to be accessed frequently through loop iterations ;
  • It is necessary to add and delete elements frequently at the beginning, middle, end , etc. of the list.

4. Common methods

LinkedListMany methods in are actually from the List interface, so many of its methods are the same as ArrayList. However, due to its own characteristics, it also has some unique common methods, and only LinkedListthe unique common methods are listed here, as shown in the following table:

method describe
public void addFirst(E e) Add an element to the head of the collection.
public void addLast(E e) Adds an element to the end of the collection.
public boolean offer(E e) Add an element to the end of the linked list, success is true, failure is false.
public boolean offerFirst(E e) Insert an element at the head of the linked list, true for success, false for failure.
public boolean offerLast(E e) Insert an element at the end of the linked list, true for success, false for failure.
public void clear() Clear the linked list.
public E removeFirst() Remove and return the first element of the linked list.
public E removeLast() Remove and return the last element of the linked list.
public boolean remove(Object o) Delete an element, success is true, failure is false.
public E remove(int index) Deletes the element at the specified position.
public E poll() Remove and return the first element.
public E remove() Remove and return the first element.
public E getFirst() Returns the first element.
public E getLast() Returns the last element.
public int lastIndexOf(Object o) Finds the index of the last occurrence of the specified element.
public E peek() Returns the first element.
public E element() Returns the first element.
public E peekFirst() Returns the head element.
public E peekLast() Returns the tail element.
public Iterator descendingIterator() Returns a reverse iterator.
public ListIterator listIterator(int index) Returns an iterator from the specified position to the end.

After a basic understanding of these methods, let's choose a few core methods to see how to use them.

5. Add/remove elements

We can addFirst()和addLast()add an element at the beginning and end of the linked list through the method. When we want to frequently add and delete elements at the beginning and end of a list, it is 要比more efficient to use ````LinkedList ArrayList```.

import java.util.LinkedList;

public class Demo09 {
    
    

	public static void main(String[] args) {
    
    
		// 创建LinkedList集合
		LinkedList<String> names = new LinkedList<String>();
		// 一个一个地添加元素
		names.add("一一哥");
		names.add("java");
		names.add("数学");

		//在链表的开头添加元素
        names.addFirst("壹壹哥");
        
        //在链表的结尾添加元素
        names.addLast("历史");

		// 遍历集合
		for (String name : names) {
    
    
			System.out.println("name=" + name);
		}

        //移除链表开头的元素
        names.removeFirst();
        //移除链表结尾的元素
        names.removeLast();
	}
}

6. Get elements iteratively

We can getFirst()、getLast()get the first and last element in the collection through the etc. method.

import java.util.LinkedList;

public class Demo10 {
    
    
	public static void main(String[] args) {
    
    
		// 创建LinkedList集合
		LinkedList<String> names = new LinkedList<String>();
		// 一个一个地添加元素
		names.add("一一哥");
		names.add("java");
		names.add("数学");

		System.out.println("first=" + names.getFirst());
		System.out.println("last=" + names.getLast());

		// 迭代遍历集合
		for (String name : names) {
    
    
			System.out.println("name=" + name);
		}
	}
}

7. Companion Video

The supporting video link for this section is as follows : click the link to go straight to the video tutorial


4. Conclusion

So far we have explained the List collection to everyone, and finally let's look at the key points of this article:

List is an ordered list of variable length accessed in index order;

In general development, ArrayList is used more frequently than LinkedList;

List and Array can be converted to each other;

There are many ways to traverse the collection, and the enhanced for loop and Iterator iterator are more efficient;

Both ArrayList and LinkedList are implementation classes of the List interface, and both implement all unimplemented methods in List, but the implementation methods are different;

The underlying data structure of ArrayList is based on dynamic arrays, and the speed of accessing elements is faster than that of LinkedList. When accessing data quickly, the execution efficiency of ArrayList is relatively high;

The underlying data structure of LinkedList is based on a linked list, which occupies a large memory space, but it is faster than ArrayList when inserting or deleting data in batches. When frequently inserting and deleting elements into the collection, it is more efficient to use LinkedList than ArrayList.


The above is the whole content of this article. If you have technical questions, welcome to communicate and discuss with us~

For more technical dry goods, follow me!

I am a sharer who specializes in sharing technical dry goods!

Guess you like

Origin blog.csdn.net/GUDUzhongliang/article/details/130767725