Java Reference
In-Depth Information
variable called
list
stores the values
[4, 3, 2, 1]
. The call of
list.printInversions();
would print many
inversions:
(4, 3)
(4, 2)
(4, 1)
(3, 2)
(3, 1)
(2, 1)
The inversions can appear in any order, so this is just one possible correct output. You must reproduce this format
exactly, but the inversions can appear in any order. You may assume that the list has no duplicates.
12.
Write a method called
mirror
that doubles the size of a list by appending the mirror image of the original sequence
to the end of the list. The mirror image is the same sequence of values in reverse order. For example, if a variable
called
list
stores
[1, 3, 2, 7]
and the client calls
list.mirror();
then the list should be changed to store
[1, 3, 2, 7, 7, 2, 3, 1]
. Notice that it has doubled in size because the original sequence now appears in
reverse order at the end of the list.
13.
Write a method called
stutter
that replaces every value with two of that value. For example, if the list initially
stores
[42, 7, 0, -3, 15]
, after the call it should store
[42, 42, 7, 7, 0, 0, -3, -3, 15, 15]
.
14.
Write a method called
stretch
that takes an integer
n
as a parameter and that increases a list of integers by a factor
of
n
by replacing each integer in the original list with
n
copies of that integer. For example, if a variable called
list
stores
[18, 7, 4, 24, 11]
and we make the call of
list.stretch(3);
the list should be changed to store
[18, 18, 18, 7, 7, 7, 4, 4, 4, 24, 24, 24, 11, 11, 11]
.
15.
Write a method called
switchPairs
that switches the order of values in the list in a pairwise fashion. Your method
should switch the order of the first two values, then switch the order of the next two, switch the order of the next
two, and so on. If the list contains an odd number of values, the final element is not moved. For example, if the list
initially stores
[10, 25, 31, 47, 52, 68, 77]
, your method should switch the first pair (
10
and
25
), the
second pair (
31
and
47
), and the third pair (
52
and
68
) to yield
[25, 10, 47, 31, 68, 52, 77]
.
Programming Projects
1.
The actual
List
interface in the
java.util
package has several methods beyond the ones implemented in this
chapter. Write a version of
ArrayList<E>
that adds some or all of these methods. The methods to add are as fol-
lows (some headers are slightly modified; see the Java API Specification for descriptions of each method):
•
public void addAll(int index, ArrayList<E> list)
•
public boolean containsAll(ArrayList<E> list)
•
public boolean equals(Object o)
•
public int lastIndexOf(Object o)
•
public boolean remove(Object o)
•
public void removeAll(ArrayList<E> list)
•
public void retainAll(ArrayList<E> list)
•
public Object[] toArray()
Search WWH ::
Custom Search