Java Reference
In-Depth Information
myList[i]
, randomly generate an index
j
and swap
myList[i]
with
myList[j]
,
as follows:
for
(
int
i =
0
; i < myList.length; i++) {
// Generate an index j randomly
int
j = (
int
) (Math.random()
* mylist.length);
myList
i
[0]
[1]
.
.
.
swap
// Swap myList[i] with myList[j]
double
temp = myList[i];
myList[i] = myList[j]
myList[j] = temp;
}
A random index [j]
8.
Shifting elements:
Sometimes you need to shift the elements left or right. Here is an
example of shifting the elements one position to the left and filling the last element with
the first element:
double
temp = myList[
0
];
// Retain the first element
myList
// Shift elements left
for
(
int
i =
1
; i < myList.length; i++) {
myList[i -
1
] = myList[i];
}
// Move the first element to fill in the last position
myList[myList.length -
1
] = temp;
9.
Simplifying coding:
Arrays can be used to greatly simplify coding for certain tasks. For
example, suppose you wish to obtain the English name of a given month by its number.
If the month names are stored in an array, the month name for a given month can be
accessed simply via the index. The following code prompts the user to enter a month
number and displays its month name:
String[] months = {
"January"
,
"February"
, ...,
"December"
};
System.out.print(
"Enter a month number (1 to 12): "
);
int
monthNumber = input.nextInt();
System.out.println(
"The month is "
+ months[monthNumber -
1
]);
If you didn't use the
months
array, you would have to determine the month name using
a lengthy multi-way
if-else
statement as follows:
if
(monthNumber ==
1
)
System.out.println(
"The month is January"
);
else if
(monthNumber ==
2
)
System.out.println(
"The month is February"
);
...
els
System.out.println(
"The month is December"
);
6.2.7 for-each Loops
Java supports a convenient
for
loop, known as a
for-each loop
or
enhanced for loop
, which
enables you to traverse the array sequentially without using an index variable. For example,
the following code displays all the elements in the array
myList
:
for
(
double
u: myList) {
System.out.println(u);
}