📜  arraylist - Java (1)

📅  最后修改于: 2023-12-03 14:39:21.129000             🧑  作者: Mango

ArrayList - Java

Introduction

ArrayList is a class in Java that implements the List interface and provides a dynamic array-like data structure. It is a part of the Java Collections Framework and is widely used by programmers to store and manipulate a group of objects.

Features
  1. Resizable Array: ArrayList internally uses a resizable array to store the elements, which means it can grow or shrink dynamically.
  2. Random Access: ArrayList provides fast access to elements through their indices, similar to an array. It supports constant-time positional access to retrieve or modify elements.
  3. Ordered Elements: ArrayList maintains the order of elements as they are inserted into the list, allowing the programmer to access them in the same order.
  4. Duplicates and Nulls: ArrayList can store duplicate elements and also allows null values.
  5. Iterable: ArrayList implements Iterable interface, which means it can be easily used in enhanced for loops or with iterator-based iteration.
  6. Efficient Lookup: With random access capability, ArrayList performs efficient lookup operations, making it suitable for scenarios that involve searching or accessing elements frequently.
Usage

To use ArrayList in your Java program, you need to import the java.util.ArrayList class. Here's an example of creating an ArrayList, adding elements, and accessing them:

import java.util.ArrayList;

public class ArrayListExample {
    public static void main(String[] args) {
        // Creating an ArrayList of Strings
        ArrayList<String> fruits = new ArrayList<>();

        // Adding elements to the ArrayList
        fruits.add("Apple");
        fruits.add("Banana");
        fruits.add("Orange");

        // Accessing elements using index
        String firstFruit = fruits.get(0);
        String lastFruit = fruits.get(fruits.size() - 1);

        // Iterating over the ArrayList
        for (String fruit : fruits) {
            System.out.println(fruit);
        }
    }
}
Common Operations
  • Adding elements to the ArrayList: add(element)
  • Removing elements from the ArrayList: remove(element) or remove(index)
  • Accessing elements: get(index)
  • Updating elements: set(index, element)
  • Checking size: size()
  • Checking if empty: isEmpty()
Performance

The performance characteristics of ArrayList can be summarized as follows:

  • Access: O(1)
  • Search: O(n)
  • Insertion: O(n)
  • Deletion: O(n)
Conclusion

ArrayList in Java provides a convenient and efficient way to store and manipulate a group of objects. It offers dynamic resizing, random access, ordered elements, and supports a wide range of operations. Understanding the features and usage of ArrayList can greatly enhance your programming skills in Java.