Skip to content

ArrayList Methods

  • Lesson
  • 2 min read
  • 3 of 3 in this chapter

Many Methods

The ArrayList object has many methods, and that's great! It allows us to have maximum flexibility when working with ArrayLists.

This doesn't mean you should always use ArrayLists over Arrays

Use Arrays when:

  • Your values don't change often
  • You know how many values are going to be in the array
  • You don't need to do any complex functionality with the items

add()

We can use add() to add items to the ArrayList, like so:

Text
ArrayList<String> names = new ArrayList<String>();

names.add("Greg");
names.add("Rodrick");
names.add("Manny");

Each new item added to an ArrayList gets added to the end. However, if you want to insert it between other items, you can do so, by specifying which index you want it to go to.

This shifts every item after it to the right. So if we insert at index 1, the previous item becomes index 2, and the rest follow.

Java
names.add(1,"Susan");

remove()

We can use remove() to remove an item at an index. When we remove an item from an ArrayList, the array shifts left.

If we remove the item at index 2, the old index 3 becomes index 2, and the rest follow.

Still following the code above, we can use it like this:

Java
names.remove(2);

set()

We can use set() to replace the current item with a new item. This causes no shift, as it's a simple replacement.

Java
names.set(1,"Frank");

get()

With get(), we can get the current value of the item in the ArrayList. This is similar to using [] and an index with normal arrays.

size()

We can use size() to get the length of the ArrayList. This is similar to length with arrays.

Let's use get() and size() to iterate through the names ArrayList.

Java
for(int i = 0; i < names.size(); i++) {
System.out.println(names.get(i));
}

// This for-each loop does the same thing, just simpler
for(String name: names) {
System.out.println(name);
}

clear()

And finally, clear(). You can use clear() when you want to remove every item in the ArrayList.

Java
names.clear();

System.out.println(names.size()); // prints 0, because it's empty now
```the ArrayL