More About ArrayList
Premium Content - Free Preview
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");
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
This is the official documentation:
Returns the index of the first occurrence of the specified element in this list, or -1 if this list does not contain the element.
int c = fruits.indexOf("cantaloupe");
This will set
2, the index of
What if you want to remove an item from the List? You use the
remove() method, which has this description:
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).
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.
This will result in an ArrayList with just 2 items:
Below the first remove method, you'll see another one with the same name but a different parameter:
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).