But… Arrays can be Tedious
An array has a fixed size, so growing it, or inserting or removing an item in the middle, means copying and shifting items yourself.
Apprentice · Java · Updated
Arrays are great at finding a slot: once an array is created, you can jump straight to any position in it.
But what if you need more space? You can't simply stretch the array. If you want to re-size an array, you must create a new, bigger array and then move all the contents into the new array.
If you need to insert an element in the middle of an array, you must shift all the elements to the right to make space.
To remove an element from the middle of an array, you then need to shift all remaining elements to the left to close the gap.
These tasks (and more) are all common tasks that need to be completed when working with arrays.
Do it: seat the first person on the waiting list
The restaurant keeps its waiting list in an array of names, in the order people arrived. When a table opens, the first person on the list is seated, and the list gets one name shorter. An array can't shrink, so the method has to build a new, shorter array.
The method gets one value:
waitingList: aString[]of names, the first to arrive first. It always has at least one name.
For example:
String[] waitingList = { "Ana", "Raj", "Lee", "Kim" };
Ana is seated. The new array has 3 places, and each place gets the name one place further along in the old array:
| New array's place | Copied from | Name |
|---|---|---|
| 0 | waitingList[1] |
Raj |
| 1 | waitingList[2] |
Lee |
| 2 | waitingList[3] |
Kim |
So removeFirst(waitingList) returns the array { "Raj", "Lee", "Kim" }.
Your job: write the method removeFirst(String[] waitingList) so it returns a new String[].
- The new array is one element shorter than
waitingList. - It holds every name but the first, in the same order.
- When the list has only one name, the new array is empty.
waitingListitself stays as it was: don't change it.
Practiced live on the lesson page: write the Java right there and check it.