Java ArrayList methods

·

1 min read

Remember that to add something at a certain index, use

listName.add(i, "Thing to be added");

where i is the index where you want the item added.

To change an item at a certain index, use

listName.set(i, "New thing");

but remember that you can only change something at an existing index with this command. If the index doesn't exist yet, you'll get an Out of Bounds error.

You can use the remove() method in two ways:

listName.remove(i);
// or
listName.remove("Thing to be removed");

Either with the index whose item you want removed or with the item itself.

.size() gives you the length of the ArrayList.

listName.size();

This returns the number of items in the list.

To return an item when you have its index, use .get()

listName.get(i);

On the other hand, if you know the item but not the index, you can use .indexOf()

listName.indexOf("Item I'm looking for");



And the constructor is as follows:

ArrayList<Non-PrimitiveType> listName = new ArrayList<Non-PrimitiveType>();