SoFunction
Updated on 2025-04-14

Summary of common usage examples of ArrayList in Java

In JavaArrayListis a very commonly used dynamic array that is part of the Java collection framework. Unlike ordinary arrays,ArrayListIt can be resized dynamically when needed. The following isArrayListSome detailed introductions:

Basic Features

  • Dynamic sizeArrayListIt 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 includenullValue.
  • Non-thread safe: Manual synchronization is required when used in a multi-threaded environment.

Common methods

  • Add elements

ArrayList<String> list = new ArrayList<>();

Add a single element:add(E e)

("apple");
  • Add in the specified location:add(int index, E element)
(1, "banana");
  • Access elements

    • By index:get(int index)
  • Modify elements

    • Modify element values:set(int index, E element)
(1, "orange");
  • Delete elements

    • Delete by index:remove(int index)
(0);
  • Delete by value (first matching element):remove(Object o)
("banana");
  • Traversal elements

for (String item : list) {
    (item);
}
  • Other common methods

    • Get the sizesize()
    • Check if it is emptyisEmpty()
    • Clear the listclear()
    • Check whether the specified element is includedcontains(Object o)
    • Get the element indexindexOf(Object o)

Performance considerations

  • Time complexity
    • Add/modify/get elements:O(1)(Average)
    • Insert/delete elements in the middle:O(n)
  • becauseArrayListImplemented based on arrays, when the initial capacity exceeds, 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&lt;String&gt; list = new ArrayList&lt;&gt;();
        // 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);
        }
    }
}

ArrayListIt is suitable for scenarios with frequent access and modification, but when performance and security requirements are high, select other collections (such asLinkedListor synchronize the list) may be more appropriate.

Yes,ArrayListOnly reference data types can be stored, and basic data types cannot be stored directly (such asintdoublecharwait). This is becauseArrayListIt 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?

AlthoughArrayListBasic data types cannot be stored directly, but Java provides an automatic boxing mechanism, which can automatically convert basic data types into corresponding packaging 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&lt;Integer&gt; intList = new ArrayList&lt;&gt;();
(10);   // Automatic boxing, convert int to Integer(20);
(30);
(intList); // Output: [10, 20, 30]

In this example,1020and30yesintTypes of data, but Java automatically converts them toInteger(Packaging Class) object and storedArrayList

Automatically unboxing when taking values

Stored inArrayListThe wrapper class object in   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

    • ifArrayListA certain element in it isnull, will be thrown when unboxingNullPointerException
    • For example:
ArrayList&lt;Integer&gt; intList = new ArrayList&lt;&gt;();
(null); // Added a nullint num = (0); // Throw out when unboxing automatically NullPointerException

What if multiple different basic data types need to be stored?

If yourArrayListIt is necessary to store multiple basic data types at the same time, and the following methods can be considered:

  • useArrayList<Object>

    • By manually boxing, store all the data into the corresponding wrapper class, and then store them in oneArrayList<Object>middle.
    • Example:
ArrayList&lt;Object&gt; list = new ArrayList&lt;&gt;();
(123);        // Storage Integer(45.67);      //Storage Double("Hello");    //Storage String(true);       //Storage Booleanfor (Object obj : list) {
    (());
}
  • 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) {
    ( + ", " +  + ", " + );
}
  • useMapor other collection structures

    • Can be usedMap<String, Object>Or similar containers, which store different types of data by key-value pairs.

Summarize

  • ArrayListOnly directly store reference types.
  • 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 useArrayList<Object>or custom class,Mapand other structures. -

This is the end of this article about the common usage of ArrayList in Java. For more related content on Java ArrayList usage, please search for my previous articles or continue browsing the related articles below. I hope everyone will support me in the future!