📜  Java ArrayList get()(1)

📅  最后修改于: 2023-12-03 15:01:28.514000             🧑  作者: Mango

Java ArrayList get()

Introduction

In Java, the ArrayList class is a resizable array implementation of the List interface. It provides dynamic arrays that can grow or shrink as needed. The get() method of the ArrayList class is used to retrieve the element at a specific index in the array.

Syntax

The syntax of the get() method is as follows:

public E get(int index)

Here, E is the type of element stored in the ArrayList. The method takes an integer index as an argument and returns the element at that index.

Parameters

The get() method takes a single parameter:

  • index - The index of the element to retrieve. The index should be within the bounds of the ArrayList, i.e., between 0 and size()-1.
Return Value

The get() method returns the element at the specified index. The type of the returned element is the same as the type of elements stored in the ArrayList.

Example

Here's a simple example that demonstrates the usage of the get() method:

import java.util.ArrayList;

public class ArrayListExample {
    public static void main(String[] args) {
        ArrayList<String> fruits = new ArrayList<>();
        fruits.add("Apple");
        fruits.add("Banana");
        fruits.add("Orange");

        String fruit = fruits.get(1);
        System.out.println(fruit);  // Output: Banana
    }
}

In this example, we create an ArrayList of String type and add three fruits to it. We then retrieve the fruit at index 1 using the get() method and print it to the console.

Notes
  • The index used in the get() method starts from 0 for the first element and goes up to size()-1 for the last element.
  • If the index provided is outside the valid range, i.e., less than 0 or greater than or equal to size(), an IndexOutOfBoundsException will be thrown.

This is how you can use the get() method of the Java ArrayList class to retrieve elements from a specific index.