ARRL - ArrayList Methods (Lesson)
ArrayList Methods
Introduction
The convenience of using an ArrayList instead of an array is that ArrayLists can grow and shrink. ArrayLists are mutable. We do not need to know the number of objects it must contain when it is created. The ArrayList methods will allow us to add, remove and modify the contents of the list. The downside is that the ArrayList must hold objects. Primitive data is not allowed to this party. ArrayLists can also take up more space than is necessary. In this lesson we will look at several useful ArrayLists methods.
The following ArrayList methods will be tested on the AP Exam. The methods are part of the Java Quick Reference which will be available for you to use during the exam.
- int size( ) – This method returns the number of elements in the ArrayList.
- boolean add ( E obj) – This method appends obj to the end of the ArrayList. It returns true.
- void add ( int index, E obj) – This method inserts obj at position index (0 = index = size). Elements at position index and higher move to the right and 1 is added to the size.
- E get(int index) – This method returns the object at the index in the ArrayList. It does not remove the object from the list.
- E set(int index, E obj) – This method will replace the object at index with obj in the ArrayList. It returns the object formerly at position index.
- E remove(int index) – This method removes the object at index in the ArrayList. Elements at position index and higher move to the left and 1 is subtracted from the size. It returns the object formerly at position index.
Digits Free Response Question, Part A
The following free response question is from a past AP Exam. Read the problem and write the constructor for part A on a sheet of paper.
Once you have written your answer watch the video below to check your work.
IMAGES CREATED BY GAVS