Java Reference
In-Depth Information
The process continues in this manner, copying the
8
from index 1 to index 2 and
copying the
3
from index 0 to index 1, leaving you with the following:
list
3
3
8
9
7
At this point, the only thing left to do is to put the
5
stored in the local variable at
the front of the list:
list
5
3
8
9
7
You can reverse the
for
loop by changing the
i++
to
i--
and adjusting the initial-
ization and test. The final method is as follows:
public static void rotateRight(int[] list) {
int last = list[list.length - 1];
for (int i = list.length - 1; i >= 1; i--) {
list[i] = list[i - 1];
}
list[0] = last;
}
All of the arrays we have looked at so far have stored primitive values like simple
int
values, but you can have arrays of any Java type. Arrays of objects behave
slightly differently, though, because objects are stored as references rather than as
data values. Constructing an array of objects is usually a two-step process, because
you normally have to construct both the array and the individual objects.
As an example, Java has a
Point
class as part of its
java.awt
package. Each
Point
object is used for storing the (
x
,
y
) coordinates of a point in two-dimensional
space. (We will discuss this class in more detail in the next chapter, but for now we
will just construct a few objects from it.) Suppose that you want to construct an array
of
Point
objects. Consider the following statement:
Point[] points = new Point[3];
This statement declares a variable called
points
that refers to an array of length 3
that stores references to
Point
objects. Using the
new
keyword to construct the array
doesn't construct any actual
Point
objects. Instead it constructs an array of length 3,
each element of which can store a reference to a
Point
. When Java constructs the
array, it auto-initializes these array elements to the zero-equivalent for the type. The
Search WWH ::
Custom Search