Java Reference
In-Depth Information
System.out.print(“\nSorted values: “);
for(int i : values) {
System.out.print(i + “ “);
}
The odd numbers appear before all the even numbers. Here is a sample output of the
previous code:
Initial values: 6 8 8 9 2 1 7 2 3 0 7 2 6 5 2
Sorted values: 9 1 7 3 7 5 6 8 8 2 2 0 2 6 2
Converting an Array to a List
You should be able to convert an array to a list, which is accomplished by using the
static
asList
method in the
Arrays
class, as follows:
public static <T> List<T> asList(T... a)
The returned
List
is fi xed in size and backed by the specifi ed array, meaning that
changes to the
List
object actually change the array, as long as you do not perform any
operations that modify the length of the
List
. For example, see if you can determine the
output of the following statements:
String [] array = {“one”, “two”, “three”};
List<String> list = Arrays.asList(array);
list.set(1, “four”);
for(String s : array) {
System.out.println(s);
}
The array contains three
String
objects, and passing it to
asList
creates a
List
with the
same three
String
objects. Setting index
1
to
“four”
changes
list
and
array
, as shown
by the output of the
for-each
loop:
one
four
three
Another use of the
asList
method is to create a fi xed-size
List
using the variable-
length arguments passed in. For example, the following statement creates a new
List
containing seven
Integer
objects:
List<Integer> numbers = Arrays.<Integer>asList(8, 6, 7, 5, 3, 0, 9);
Just remember that
asList
returns a fi xed-size List. Attempting to add or remove an
element from numbers results in an
UnsupportedOperationException
at runtime.
Search WWH ::
Custom Search