Introduction to Java List
In Java,List
An interface is part of the collection framework that defines an ordered collection that allows the storage of duplicate elements and can be accessed through the index.List
Inherited fromCollection
Interface, provides additional functionality to handle ordered collections.List
The main features include:
- Orderful: The order of accessing elements is consistent with the order during insertion.
- Repeatability: Allows to store duplicate elements.
- Index access: Elements can be accessed and manipulated through integer indexes.
CommonList
Implementation class hasArrayList
、LinkedList
、Vector
andStack
wait. in,ArrayList
Based on dynamic array implementation, suitable for frequent random access;LinkedList
Based on the bidirectional linked list, it is more suitable for frequent insertion and deletion operations.
List common methods
The following isList
Some common methods and example codes for interfaces:
-
Add elements
-
add(E e)
: Add an element to the end of the list. -
add(int index, E element)
: Insert an element at the specified position, and the original element will move backwards. -
addAll(Collection<? extends E> c)
: Add all elements in the specified collection to the end of the list in order. -
addAll(int index, Collection<? extends E> c)
: Starting from the specified location, insert all elements in the specified collection into the list.
import ; import ; public class ListAddExample { public static void main(String[] args) { List<String> list = new ArrayList<>(); ("Apple"); ("Banana"); (1, "Orange"); // Insert "Orange" at index 1 ("After adding elements: " + list); List<String> moreFruits = new ArrayList<>(); ("Grape"); ("Peach"); (moreFruits); // Add to the end (1, moreFruits); //Add from index 1 ("After adding all elements: " + list); } }
-
-
Get elements
-
get(int index)
: Returns the element at the specified position in the list. -
indexOf(Object o)
: Returns the index of the specified element that appears for the first time; if not found, return -1. -
lastIndexOf(Object o)
: Returns the index of the specified element that appeared last; if not found, returns -1.
import ; import ; public class ListGetExample { public static void main(String[] args) { List<String> list = new ArrayList<>(); ("Apple"); ("Banana"); ("Orange"); String fruit = (1); // Get the element at index 1 ("Element at index 1: " + fruit); int index = ("Orange"); // Find the index of "Orange" ("Index of 'Orange': " + index); int lastIndex = ("Banana"); // Find the last "Banana" index ("Last index of 'Banana': " + lastIndex); } }
-
-
Modify elements
-
set(int index, E element)
: Replace elements at the specified position in the list with the specified element and return the replaced element.
import ; import ; public class ListSetExample { public static void main(String[] args) { List<String> list = new ArrayList<>(); ("Apple"); ("Banana"); ("Orange"); String oldFruit = (1, "Grape"); // Modify the element at index 1 ("Replaced element: " + oldFruit); ("Updated list: " + list); } }
-
-
Delete elements
-
remove(int index)
: Removes the element at the specified position in the list and returns the removed element. -
remove(Object o)
: Removes the first occurrence of the specified element in the list (only if it exists), and returnstrue
, otherwise returnfalse
。
import ; import ; public class ListRemoveExample { public static void main(String[] args) { List<String> list = new ArrayList<>(); ("Apple"); ("Banana"); ("Orange"); String removedFruit = (1); // Remove the element at index 1 ("Removed element: " + removedFruit); ("Updated list: " + list); boolean isRemoved = ("Apple"); // Remove the first "Apple" ("Is 'Apple' removed? " + isRemoved); ("Final list: " + list); } }
-
-
Query elements
-
contains(Object o)
: If the list contains the specified element, returntrue
。 -
isEmpty()
: If the list does not contain any elements, returntrue
。
import ; import ; public class ListQueryExample { public static void main(String[] args) { List<String> list = new ArrayList<>(); ("Apple"); ("Banana"); ("Orange"); boolean containsBanana = ("Banana"); ("Does the list contain 'Banana'? " + containsBanana); boolean isEmpty = (); ("Is the list empty? " + isEmpty); } }
-
-
Other operations
-
clear()
: Remove all elements from the list. -
size()
: Returns the number of elements in the list. -
iterator()
: Returns an iterator for iterating through elements in the list. -
listIterator()
: Return oneListIterator
, can traverse the list in both directions and support adding or removing elements during the traversal.
import ; import ; import ; import ; public class ListOtherOperationsExample { public static void main(String[] args) { List<String> list = new ArrayList<>(); ("Apple"); ("Banana"); ("Orange"); ("List size: " + ()); Iterator<String> iterator = (); while (()) { ("Iterator: " + ()); } ListIterator<String> listIterator = (); while (()) { ("ListIterator forward: " + ()); } while (()) { ("ListIterator backward: " + ()); } (); // Clear the list ("Is the list empty after clearing? " + ()); } }
-
Five ways to traverse
-
Iterator
- use
Iterator
The interface provideshasNext()
andnext()
Method to iterate over the list. This approach is suitable for situations where elements need to be removed during traversal, becauseIterator
Provides the ability to remove elements safely, avoidingConcurrentModificationException
risk.
import ; import ; import ; public class IteratorTraversalExample { public static void main(String[] args) { List<String> list = new ArrayList<>(); ("Apple"); ("Banana"); ("Orange"); Iterator<String> iterator = (); while (()) { String item = (); (item); if ("Banana".equals(item)) { (); // Safely remove the current element } } ("List after removal: " + list); } }
- use
-
Enhanced for loop
- Enhanced for loops (also known as foreach loops) provide a cleaner way to traverse
List
, no need to explicitly manage indexes. The code is clearer and easier to read, suitable for scenarios where index information is not required.
import ; import ; public class EnhancedForLoopTraversalExample { public static void main(String[] args) { List<String> list = new ArrayList<>(); ("Apple"); ("Banana"); ("Orange"); for (String item : list) { (item); } } }
- Enhanced for loops (also known as foreach loops) provide a cleaner way to traverse
-
Normal for loop
- Using traditional for loops is traversal
List
One of the most direct ways. This method allows you to access elements in the list through the index, which is suitable for situations where you need to know the current element position or need to operate based on the index.
import ; import ; public class ForLoopTraversalExample { public static void main(String[] args) { List<String> list = new ArrayList<>(); ("Apple"); ("Banana"); ("Orange"); for (int i = 0; i < (); i++) { ("Index " + i + ": " + (i)); } } }
- Using traditional for loops is traversal
-
Stream API(Java 8+)
- Introduced since Java 8
Stream
The API provides powerful functions for collection operations, including but not limited to filtering, mapping, sorting, etc. It allows for the writing of complex collection operation logic in a declarative manner and can be easily converted into parallel streams, thereby leveraging the advantages of multi-core processors to speed up processing speeds.
import ; import ; public class StreamApiTraversalExample { public static void main(String[] args) { List<String> list = new ArrayList<>(); ("Apple"); ("Banana"); ("Orange"); ().forEach(::println); // Single threaded traversal // Or use parallel streams // ().forEach(::println); } }
- Introduced since Java 8
-
List Iterator (ListIterator)
-
ListIterator
yesIterator
a subinterface forList
gather. Not only does it support bidirectional traversal (forward and backward), it can also add or delete elements during the traversal. This makesListIterator
Very useful in certain scenarios.
import ; import ; import ; public class ListIteratorTraversalExample { public static void main(String[] args) { List<String> list = new ArrayList<>(); ("Apple"); ("Banana"); ("Orange"); ListIterator<String> listIterator = (); while (()) { String item = (); ("Forward: " + item); if ("Banana".equals(item)) { ("Grape"); // Add new element after the current element } } ("List after addition: " + list); while (()) { String item = (); ("Backward: " + item); if ("Banana".equals(item)) { (); // Remove the current element } } ("List after removal: " + list); } }
-
Summarize
List
Interfaces and common implementation classes such asArrayList
andLinkedList
It is an indispensable part of Java programming and provides rich APIs to handle ordered collections. Through understandingList
The characteristics and common methods, and mastering five traversal methods, developers can choose the most appropriate way to operate according to specific needs.List
gather. Whether it is simple traversal or complex collection operations, Java provides flexible and efficient solutions.
This is the article about the introduction of List in Java, common methods and five traversal methods. For more information about common methods and traversal methods of Java List, please search for my previous articles or continue browsing the related articles below. I hope everyone will support me in the future!