PAL Worksheet ArrayList CSC20
Ex. 1) Write Java code to create a standard integer array called std_array of
size 3, and an Integer ArrayList called ‘array_list’. Provide each the following
elements: [0, 2, 4].
Ex. 2) Now, expand the Problem 1 code by inserting the elements [6, 8, 10] at
the end of both std_array and array_list. You will need to re-size std_array. You
could do this by writing a method that creates a new array that is twice the
size of an incoming array and copies the elements over before returning it.
Look up other ArrayList method to retrieve (get), delete (remove) and change
(set) elements. Notice that arraylists have indices much the same as a regular
array! Many of the ArrayList methods use indices to search and manipulate
arraylists. For example:
We can retrieve the element 4 at index 2 in the ArrayList from Problem 2
using the get method.
// array_list contains Integers [0,2,4,6,8,10]
array_list.get(2);
Ex. 3) To practice getting items, write a Java method which can reverse our
array_list. First, create a new empty ArrayList called temp. Then iterate
through array_list backwards, and within each loop cycle, retrieve an element
from array_list using get(), and use add() to insert it into temp. Use the method
size() to get the size of an ArrayList.
ArrayLists also have the remove() method to delete elements by index
position. The method dynamically re-arranges the remaining elements after
the deletion.
Ex. 4) Given the following Integer ArrayList scores_list of student exam scores:
[84, 70, 90, 67, 77, 94, 92, 71, 80, 95], write some lines of code that remove all
the odd-valued scores, i.e. 67, 77, 71 and 95
It’s often important to remove duplicate elements in an ArrayList. Look up the
remove method version that removes objects by value. Note that
remove(value) will remove the first occurrence of the provided value. What if
there are multiple occurrences of the value?