collapse
Category: ArrayList
Author: Stuart Reges
Book Chapter: 10.1
Problem: collapse
Write a static method called collapse that takes an
ArrayList of Strings as a parameter and that collapses successive pairs into
a single String. Each pair should be collapsed into a new String that has
the two values inside parentheses and separated by a comma. For example, if
a variable called "list" initially stores these values:
["four", "score", "and", "seven", "years", "ago"]
and we make the following call:
collapse(list);
Your method should collapse the first pair into "(four, score)", the second
pair into "(and, seven)" and the third pair into "(years, ago)" so that list
stores the following values:
["(four, score)", "(and, seven)", "(years, ago)"]
Notice that the list goes from having 6 elements to having 3 elements
because each successive pair is collapsed into a single value. If there are
an odd number of values in the list, the final element is not collapsed.
For example, if the original list had been:
["to", "be", "or", "not", "to", "be", "hamlet"]
It would again collapse pairs of values, but the final value ("hamlet")
would not be collapsed, yielding this list:
["(to, be)", "(or, not)", "(to, be)", "hamlet"]
Recall that the primary methods for manipulating an ArrayList are:
add(E value) appends value at end of list
add(int index, E value) inserts given value at given index, shifting
subsequent values right
clear() removes all elements of the list
get(int index) returns the value at given index
remove(int index) removes and returns value at given index,
shifting subsequent values left
set(int index, E value) replaces value at given index with given value
size() returns the number of elements in list
Write your solution to collapse below.