Accessing and Removing Values from an ArrayList Object
E get (int index)
The method returns the element at index.
Your Turn
Let's try it in the Java Playground.
- Predict the output of the code.
- Run the code to determine if your prediction is correct.
- Write code to get the first and last elements of
studentList. Predict the output of the code and run it to determine if your prediction is correct.
- Write code to attempt to get the value at element
5. What happens when you attempt to access an element that does not exist?
E remove (int index)
The method removes the element at the given index and returns the element. Any elements to the right of this element are shifted to the left and the size of the ArrayList is decreased by 1.
Your Turn
Let's try it in the Java Playground.
- Predict the output of the code.
- Run the code to determine if your prediction is correct.
- Write code to remove the first element of
studentList. Predict the output of the code and run it to determine if your prediction is correct.
- Write code to remove the element at index 3 of
studentList. Predict the output of the code and run it to determine if your prediction is correct.
booleam remove (Object o)
The method removes the first occurrence of Object o if it exists and returns true. If Object o does not exist, the ArrayList is unchanged and false is returned.
Your Turn
Let's try it in the Java Playground.
- Predict the output of the code.
- Run the code to determine if your prediction is correct.
- Attempt to remove "Susie" from the list. Predict the output of the code and run it to determine if your prediciton is correct.
Complete List of ArrayList Tutorials
Resources