Explain Codes LogoExplain Codes Logo

Get specific ArrayList item

java
indexing
null-checks
optional
Anton ShumikhinbyAnton Shumikhin·Feb 8, 2025
TLDR

To grab an element from an ArrayList, invoke the .get(index) with the element's index. Note that indices start at 0. Here's a quick example:

ArrayList<String> fruits = new ArrayList<>(Arrays.asList("Apple", "Banana", "Cherry")); String fruit = fruits.get(1); // Gobbles up "Banana"

Be sure your index is valid or Java will gift you with an IndexOutOfBoundsException.

Understanding ArrayList indices in Java

Java's ArrayList follows zero-based indexing, which means the party starts at 0, not 1.

ArrayList<String> dogBreeds = new ArrayList<>(Arrays.asList("Bulldog", "Beagle", "Bichon Frise")); String thirdDog = dogBreeds.get(2); // unreleases the Bichon Frise

// In Java, the third dog's the charm. 🐶

Dealing with IndexOutOfBoundsException

Java will deal you an IndexOutOfBoundsException when you try to access an index that isn't in the game.

String missingDog = dogBreeds.get(5); // Throws IndexOutOfBoundsException

// This is Java's way of saying "Hey, there's no sixth dog here!".

To avoid this, always cross-check the size of your ArrayList before trying to access an element.

int index = 5; if(index < dogBreeds.size()){ String safeDog = dogBreeds.get(index); }

Correct and Incorrect Array Item Syntax

In Java, attempting to use the array access syntax ([]) with ArrayList is a rookie error and will only reward you with a compile-time error.

// Don't do this String canine = dogBreeds[1]; // A syntax error, but nice try! // Do this instead String canine = dogBreeds.get(1); // Fetches "Beagle"

// Note: Java can be unforgiving if you don't follow its rules!

Power-ups: Advanced ArrayList manipulations

Looping over an ArrayList

If you need to access all elements sequentially, use the enhanced for loop:

for (String breed : dogBreeds) { System.out.println(breed); } // Prints: Bulldog, Beagle, Bichon Frise

Playing with Stream API

Java 8 introduced the beautiful Stream API for operations like filtering:

dogBreeds.stream() .filter(breed -> breed.startsWith("B")) .forEach(System.out::println); // Prints: Bulldog, Beagle

// Yes, only the good boys starting with 'B'!

When ArrayList is not enough: Converting ArrayList to an Array

For those times when ArrayList is not the right tool, you can turn it into an Array:

String[] dogArray = new String[dogBreeds.size()]; dogBreeds.toArray(dogArray); // POOF! You now have an array

Null Checks & Optionals in ArrayList

Avoid NullPointerException: always check for nulls

Remember that ArrayList can contain null values. Always check for null before using a retrieved item:

// Brings back Banana or null if index not valid String fruit = fruits.get(2); if(fruit != null) { // Now you are safe! Enjoy your fruit. }

Embrace Optionals: handle potential nulls with ease

Java 8 introduced Optional, which reduces risks of NullPointerExceptions and makes your code cleaner:

// If fruits.get(2) is null, "Default Fruit" will be assigned to fruit String fruit = Optional.ofNullable(fruits.get(2)).orElse("Default Fruit");