In JavaArrayList
is a very commonly used dynamic array that is part of the Java collection framework. Unlike ordinary arrays,ArrayList
It can be resized dynamically when needed. The following isArrayList
Some detailed introductions:
Basic Features
-
Dynamic size:
ArrayList
It will automatically resize to suit new elements. - Ordered collection: Elements are stored in the order of insertion, but can be accessed through indexes.
- Repeat allowed: Can contain duplicate elements.
-
Allow null values: Can include
null
value. - Non-thread safe: Manual synchronization is required when used in a multi-threaded environment.
Common methods
-
Create an ArrayList
ArrayList<String> list = new ArrayList<>();
-
Add elements
- Add a single element:
add(E e)
("apple");
- Add in the specified location:
add(int index, E element)
(1, "banana");
- Add a single element:
-
Access elements
- By index:
get(int index)
String fruit = (0);
- By index:
-
Modify elements
- Modify element values:
set(int index, E element)
(1, "orange");
- Modify element values:
-
Delete elements
- Delete by index:
remove(int index)
(0);
- Delete by value (first matching element):
remove(Object o)
("banana");
- Delete by index:
-
Traversal elements
for (String item : list) { (item); }
-
Other common methods
-
Get the size:
size()
-
Check if it is empty:
isEmpty()
-
Clear the list:
clear()
-
Check whether the specified element is included:
contains(Object o)
-
Get the element index:
indexOf(Object o)
-
Get the size:
Performance considerations
-
Time complexity:
- Add/modify/get elements:
O(1)
(Average) - Insert/delete elements in the middle:
O(n)
- Add/modify/get elements:
- because
ArrayList
Implemented based on arrays, when the initial capacity is exceeded, it may be necessary to reassign the array, which involves copying of the original array to the new array.
Example of usage
import ;
public class ArrayListExample {
public static void main(String[] args) {
ArrayList<String> list = new ArrayList<>();
// Add elements
("apple");
("banana");
("cherry");
// Insert element
(1, "orange");
// Access and modify elements
String fruit = (0);
(1, "kiwi");
// Delete elements
("banana");
// Output list
for (String item : list) {
(item);
}
}
}
ArrayList
It is suitable for frequent access and modification scenarios, but when performance and security requirements are high, select other collections (such asLinkedList
or sync list) may be more appropriate.
Yes,ArrayList
Only referenced data types are stored, the basic data types cannot be stored directly (such asint
、double
、char
wait). This is becauseArrayList
It is implemented based on Java generics, and generics only support object types (reference types) and do not support basic data types.
How to store basic data types?
AlthoughArrayList
Basic data types cannot be stored directly, but Java provides an automatic boxing mechanism, which can automatically convert basic data types into corresponding wrapper classes, so that they indirectly store basic data types.
Common basic data types and their corresponding packaging classes
Basic data types | Packaging class (reference type) |
---|---|
int |
Integer |
double |
Double |
char |
Character |
boolean |
Boolean |
float |
Float |
long |
Long |
short |
Short |
byte |
Byte |
Example:
ArrayList<Integer> intList = new ArrayList<>();
(10); // Automatic boxing, convert int to Integer
(20);
(30);
(intList); // Output: [10, 20, 30]
In this example,10
、20
and30
yesint
Types of data, but Java automatically converts them toInteger
(Packaging Class) object and storedArrayList
。
Automatically unboxing when taking values
Stored inArrayList
The wrapper class object in it will automatically convert back to the basic data type when needed (called "unboxing").
Example:
int sum = 0;
for (int num : intList) { // Automatically unbox, convert Integer to int
sum += num;
}
("Sum:" + sum);
Things to note
-
performance
- Although automatic packing and unboxing are easy to use, it will increase certain performance overhead, especially during frequent operations.
-
Avoid null pointer exceptions
- if
ArrayList
An element innull
, will be thrown when unboxingNullPointerException
。 - For example:
ArrayList<Integer> intList = new ArrayList<>(); (null); // Added a null int num = (0); // throw NullPointerException when unboxing automatically
- if
What if multiple different basic data types need to be stored?
If yoursArrayList
It is necessary to store multiple basic data types at the same time, and the following methods can be considered:
-
use
ArrayList<Object>
- By manually boxing, store all the data as corresponding wrapper classes, and then store them in one
ArrayList<Object>
middle. - Example:
ArrayList<Object> list = new ArrayList<>(); (123); // Storage Integer (45.67); // Store Double ("Hello"); //Storage String (true); // Store Boolean for (Object obj : list) { (()); }
- By manually boxing, store all the data as corresponding wrapper classes, and then store them in one
-
Encapsulation using custom classes
- Customize a class and save all required data types as fields of the class.
- Example:
class Data { int intValue; double doubleValue; String stringValue; Data(int intValue, double doubleValue, String stringValue) { = intValue; = doubleValue; = stringValue; } } ArrayList<Data> dataList = new ArrayList<>(); (new Data(10, 20.5, "Hello")); for (Data data : dataList) { ( + ", " + + ", " + ); }
-
use
Map
or other collection structure- Available
Map<String, Object>
Or similar containers, which store different types of data by key-value pairs.
- Available
Summarize
ArrayList
Only reference types can be stored directly.- If you want to store basic data types, it can be implemented through packaging classes, relying on automatic boxing and unboxing mechanisms.
- For data that requires mixed storage of multiple types, you can use
ArrayList<Object>
or custom class,Map
and other structures. -