Java Reference
In-Depth Information
System.out.println(
"(2) Index: "
+ Collections.binarySearch(list1,
9
));
List<String> list2 = Arrays.asList(
"blue"
,
"green"
,
"red"
);
System.out.println(
"(3) Index: "
+
Collections.binarySearch(list2,
"red"
));
System.out.println(
"(4) Index: "
+
Collections.binarySearch(list2,
"cyan"
));
The output of the preceding code is:
(1) Index: 2
(2) Index: -4
(3) Index: 2
(4) Index: -2
You can use the
reverse
method to reverse the elements in a list. For example, the following
code displays
[blue, green, red, yellow]
.
reverse
List<String> list = Arrays.asList(
"yellow"
,
"red"
,
"green"
,
"blue"
);
Collections.reverse(list);
System.out.println(list);
You can use the
shuffle(List)
method to randomly reorder the elements in a list. For
example, the following code shuffles the elements in
list
.
shuffle
List<String> list = Arrays.asList(
"yellow"
,
"red"
,
"green"
,
"blue"
);
Collections.shuffle(list);
System.out.println(list);
You can also use the
shuffle(List, Random)
method to randomly reorder the elements in
a list with a specified
Random
object. Using a specified
Random
object is useful to generate a
list with identical sequences of elements for the same original list. For example, the following
code shuffles the elements in
list
.
List<String> list1 = Arrays.asList(
"yellow"
,
"red"
,
"green"
,
"blue"
);
List<String> list2 = Arrays.asList(
"yellow"
,
"red"
,
"green"
,
"blue"
);
Collections.shuffle(list1,
new
Random(
20
));
Collections.shuffle(list2,
new
Random(
20
));
System.out.println(list1);
System.out.println(list2);
You will see that
list1
and
list2
have the same sequence of elements before and after the
shuffling.
You can use the
copy(det, src)
method to copy all the elements from a source list to a
destination list on the same index. The destination list must be as long as the source list. If it is
longer, the remaining elements in the source list are not affected. For example, the following
code copies
list2
to
list1
.
copy
List<String> list1 = Arrays.asList(
"yellow"
,
"red"
,
"green"
,
"blue"
);
List<String> list2 = Arrays.asList(
"white"
,
"black"
);
Collections.copy(list1, list2);
System.out.println(list1);
Search WWH ::
Custom Search