1. Introduction
In Java programming, we often need to process data from multiple elements. Arrays are a basic way to store data, but they have some limitations, such as fixed lengths. In order to process data more flexibly, Java provides a collection framework that can automatically resize based on the addition or removal of elements, and provides a rich operating method.
2. Why do you need a collection?
2.1 Disadvantages of arrays
When we want to store multiple elements at the same time, we first think of arrays. For example:
int[] arr = new int[3];
The advantage of arrays is that they can quickly access elements and can directly locate elements through indexes. However, the length of the array is fixed. Once the array is created, its length cannot be changed. If we need to store more elements, we need to create a new array and copy the elements of the original array in the past, which undoubtedly increases the complexity and performance overhead of the code.
2.2 Advantages of collections
The emergence of sets solves the problem of fixed array length. The length of the collection is variable and can be automatically expanded as the elements are added. For example, we can useArrayList
To store multiple elements without worrying about length limitations.
2.3 Features of collection storage data types
2.3.1 Array storage type
Arrays can store both basic data types and referenced data types. For example:
int[] arr1 = new int[3]; // Store basic data typesclass User { String name; int age; public User(String name, int age) { = name; = age; } } User u1 = new User("Little Red", 13); User u2 = new User("Xiao Ming", 13); User[] userArr = new User[2]; userArr[0] = u1; userArr[1] = u2; //Storing reference data types
2.3.2 Collection storage type
A collection can only store reference data types. If you want to store the basic data type, you need to convert it to the corresponding wrapper class. This is because the Java collection framework is implemented based on generics, and generics can only accept reference types. For example, to store integers, we need to useInteger
Packaging category:
import ; ArrayList<Integer> list = new ArrayList<>(); (1); // Automatic boxing, convert 1 of type int to Integer
2.4 Comparison between collections and arrays
Comparison items | Array | gather |
---|---|---|
length | The length is fixed and cannot be changed after creation | Variable length, can be automatically adjusted according to the number of elements |
Storage Type | Can store basic data types and reference data types | Only reference data types can be stored. You need to use a wrapper class to store basic data types. |
Operational flexibility | The operation is relatively simple, mainly through index access and modify elements | Provides rich operating methods, such as adding, deleting, modifying, searching, etc. |
3. Collection: ArrayList
3.1 ArrayList Overview
ArrayList
It is one of the most commonly used classes in the Java collection framework, and it implementsList
Interface, the underlying implementation is based on arrays.ArrayList
Allows to store duplicate elements and can be dynamically resized as needed.
3.2 Create an ArrayList object
import ; public class ArrayListExample { public static void main(String[] args) { // 1. Create the object of the collection // Generics: Qualify the data type stored in the collection ArrayList<String> list = new ArrayList<String>(); // After JDK 7, the types of generics can be omitted, but the front and back must be consistent, that is, the <> on the right can be written without writing // At this time we create an ArrayList object, and ArrayList is a class that has been written in Java // This class has done some processing at the bottom of the page, and the printing object is not the address value, but the content in the collection // When displaying, it will frame the contents with [] (list); } } // Running result: []
In the above code, we created aArrayList
Object, and the generic type is specified asString
, means that the collection can only be storedString
Elements of type.
3.3 The underlying implementation principle of ArrayList
ArrayList
The underlying layer uses a dynamic array to store elements. When we create aArrayList
When an object is used, an initial capacity is assigned by default (usually 10). When adding elements, if the array is insufficient,ArrayList
The capacity will be automatically expanded. The process of scaling is to create a new array with a capacity of usually 1.5 times that of the original array, and then copy the elements of the original array into the new array.
3.4 ArrayList member method
Method name | illustrate |
---|---|
boolean add (E e) | Add an element, the return value indicates whether it is successfully added |
boolean remove (E e) | Delete the specified element, the return value indicates whether it is deleted successfully |
E set (int index , E e) | Modify the element under the specified index and return the original element |
E get (int index) | Get the element of the specified index |
E remove (int index) | Delete the element under the specified index and return the original element |
int size () | The length of the set, that is, the number of elements in the set |
3.4.1 Adding elements
import ; public class ArrayListAddExample { public static void main(String[] args) { ArrayList<String> list = new ArrayList<>(); boolean b1 = ("aaa"); ("bbb"); ("ccc"); (list); (b1); } }
add(E e)
The method is used to add elements to the collection, and the return value indicates whether the addition is successful. existArrayList
In , this method usually returnstrue
, because it can always add elements successfully.
3.4.2 Delete elements
import ; public class ArrayListRemoveExample { public static void main(String[] args) { ArrayList<String> list = new ArrayList<>(); ("aaa"); ("bbb"); ("ccc"); ("aaa"); (list); } }
remove(E e)
The method is used to delete the specified element, and the return value indicates whether the delete is successful. If the element exists in the collection, delete and returntrue
; otherwise returnfalse
。
3.4.3 Modify elements
import ; public class ArrayListSetExample { public static void main(String[] args) { ArrayList<String> list = new ArrayList<>(); ("aaa"); ("bbb"); (0, "ddd"); (list); } }
set(int index, E e)
The method is used to modify the element under the specified index and return the original element.
3.4.4 Get elements
import ; public class ArrayListGetExample { public static void main(String[] args) { ArrayList<String> list = new ArrayList<>(); ("aaa"); ("bbb"); String s = (0); (s); } }
get(int index)
Method is used to get the element of the specified index.
3.4.5 Delete elements of the specified index
import ; public class ArrayListRemoveIndexExample { public static void main(String[] args) { ArrayList<String> list = new ArrayList<>(); ("aaa"); ("bbb"); String removed = (0); (list); (removed); } }
remove(int index)
The method is used to delete the element under the specified index and return the original element.
3.4.6 Get the collection length
import ; public class ArrayListSizeExample { public static void main(String[] args) { ArrayList<String> list = new ArrayList<>(); ("aaa"); ("bbb"); int size = (); (size); } }
size()
The method is used to get the length of the set, that is, the number of elements in the set.
3.4.7 Traversing the collection
import ; public class ArrayListTraversalExample { public static void main(String[] args) { ArrayList<String> list = new ArrayList<>(); ("aaa"); ("bbb"); ("ccc"); // Normal for loop traversal for (int i = 0; i < (); i++) { ((i)); } // Enhanced for loop traversal for (String element : list) { (element); } // Use iterator to traverse <String> iterator = (); while (()) { (()); } } }
In the above code, we show three types of traversalsArrayList
Method: Normalfor
Cycle, enhancementfor
Loops and iterators. Different traversal methods are suitable for different scenarios, for example, ordinaryfor
Loops can modify elements during traversal and enhancefor
Loops and iterators are simpler.
4. Performance analysis of ArrayList
4.1 Time complexity
- Add elements: The time complexity of adding elements at the end of the list is (O(1)), but adding elements in the middle or at the beginning requires moving subsequent elements, and the time complexity is (O(n)).
- Delete elements: The time complexity of deleting the end element is (O(1)). Deleting the middle or beginning element requires moving the subsequent element, and the time complexity is (O(n)).
- Find elements: The time complexity of finding elements through index is (O(1)), and the list needs to be traversed by element values, and the time complexity is (O(n)).
- Modify elements: The time complexity of modifying elements through index is (O(1)).
4.2 Space complexity
ArrayList
The space complexity mainly depends on the number of stored elements and the capacity of the array. During capacity expansion, a certain amount of space will be allocated, so the space complexity is (O(n)).
5. Summary
The complexity is (O(1)), deleting the intermediate or opening element requires moving the subsequent element, and the time complexity is (O(n)).
- Find elements: The time complexity of finding elements through index is (O(1)), and the list needs to be traversed by element values, and the time complexity is (O(n)).
- Modify elements: The time complexity of modifying elements through index is (O(1)).
5.2 Space complexity
ArrayList
The space complexity mainly depends on the number of stored elements and the capacity of the array. During capacity expansion, a certain amount of space will be allocated, so the space complexity is (O(n)).
ArrayList
It is a very practical class in the Java collection framework. It provides the function of dynamic arrays to facilitate us to store and manipulate multiple elements. By understandingArrayList
The underlying implementation principles, member methods and performance characteristics of we can use it more reasonably in actual development to improve the performance and maintainability of the code. At the same time, we should also pay attention toArrayList
In some scenarios, such as in scenarios where elements are frequently inserted and deleted, the performance may be inferior to other collection classes, such asLinkedList
。
This is the article about the Java ArrayList collection's new posture for unlocking data storage. For more related Java ArrayList collection data storage content, please search for my previous articles or continue browsing the related articles below. I hope everyone will support me in the future!