Write a public class named NumberList. This class is going to
represent an expandable list of numbers with methods for accessing
individual numbers and also for getting information about the whole list,
such as the average of all the numbers.
Add two instance variables, an int[]
called numbers and an int
called size. They should be—as most instance variables
are—private. The array numbers will be used to
hold the numbers added to this object. And size will always
be the number of numbers that have been added to the object.
Write a constructor that takes an int argument and
initializes the instance variable numbers to be an array of
that size. The size variable should be initialized
to 0 since the size of a NumberList before any
numbers have been added is indeed zero. (Note that there’s a difference
between the size of the underlying array and the logical size of the
list.)
Write a method size that takes no arguments and returns the
value of size.
Write a method add that takes an int argument
and adds the value to the array of numbers, using size as
the index. It should then increment size so the next number
will be added at the next position of the array.
Modify the add method so if it is called when the array is
full (i.e. size is equal to the length of the array) it
makes a new array twice the size of the old array, copies the elements
from the old array into it, and then adds the new number.
Write a method get that takes a single int
argument and returns the element at that index of the numbers
but only if the argument is less than size. If it is negative
or greater or equals than size you should execute the statement:
throw new IndexOutOfBoundsException(i) where i
is the argument. (This is a feature of Java that is not part of the AP
curriculum but I’ll explain it briefly in class.)
Write a method removeLast that “removes” the last element in
the list by decrementing size so that future attemps to
access it via get will fail. Return the number that was
“removed”. If size is zero, you should execute the
statement throw new IndexOutOfBoundsException().
Write a method sum that returns the sum of the elements in
the list, i.e. all the numbers that have been added and not removed.