Location>code7788 >text

Common usage of ArrayList in Java

Popularity:969 ℃/2025-02-25 15:52:49

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

  1. Dynamic sizeArrayListIt will automatically resize to suit new elements.
  2. Ordered collection: Elements are stored in the order of insertion, but can be accessed through indexes.
  3. Repeat allowed: Can contain duplicate elements.
  4. Allow null values: Can includenullvalue.
  5. 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");
      
  • Access elements

    • By index:get(int index)
      String fruit = (0);
      
  • 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 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);
         }
     }
 }

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

Yes,ArrayListOnly referenced data types are stored, the 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 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,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 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

  1. performance

    • Although automatic packing and unboxing are easy to use, it will increase certain performance overhead, especially during frequent operations.
  2. Avoid null pointer exceptions

    • ifArrayListAn 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

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

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

  1. useArrayList<Object>

    • By manually boxing, store all the data as corresponding wrapper classes, and then store them in oneArrayList<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) {
           (());
       }
  2. 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) {
          ( + ", " +  + ", " + );
      }
      
  3. useMapor other collection structure

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

Summarize

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