More About ArrayList


Premium Content - Free Preview

More Methods

Let's look at some more common methods in ArrayList. The example code below will (again) come after the following code:

 ArrayList<String> fruits = new ArrayList<String>();
 fruits.add("apple");
 fruits.add("banana");
 fruits.add("cantaloupe");

indexOf(Object o)
Sometimes you will want to search through your list to find a specific Object. With an array, you would need to write multiple lines of code that loop through the array looking for the item. With an ArrayList, you can just use the provided method indexOf. It will search through the list and return the index of the first occurrence of the Object. If the Object isn't there. it will return -1 instead.

This is the official documentation:

indexOf(Object o)
Returns the index of the first occurrence of the specified element in this list, or -1 if this list does not contain the element.

For example:

int c = fruits.indexOf("cantaloupe");

This will set c to 2, the index of cantaloupe.

remove(index)
What if you want to remove an item from the List? You use the remove() method, which has this description:

remove(int index)
Removes the element at the specified position in this list.

If you click on the method name, you'll be brought to the longer description, which adds:

Shifts any subsequent elements to the left (subtracts one from their indices).

So remove() will remove the item from the specified index and then shift all of the items over to fill the gap. ArrayList always makes sure to keep all of the items in a list together with no gaps! This way the 7th item in a list will always be located at the 7th index location.

fruits.remove(1);

This will result in an ArrayList with just 2 items:
{"apple", "cantaloupe"}

remove(Object o)
Below the first remove method, you'll see another one with the same name but a different parameter:

remove(Object o)
Removes the first occurrence of the specified element from this list, if it is present.

This method searches through the List for the given Object and will remove the first occurrence that it finds. It will return true if it finds the Object and false otherwise (though you can ignore what it returns).


End of Free Content Preview. Please Sign in or Sign up to buy premium content.

Comments

  • Can I have some help? For some reason I cannot add notes to notebook.

    import java.util.ArrayList;

    public class Notebook
    {

    private ArrayList notes;

    cont...
  • @BentheMuffin, you'll want to set a type when you create the ArrayList. See ArrayList Type.

Contact Us
Sign in or email us at [email protected]