Java Reference
In-Depth Information
11.32
Suppose the
ArrayList list
contains
{"Dallas", "Dallas", "Houston",
"Dallas"}
. What is the list after invoking
list.remove("Dallas")
one time?
Does the following code correctly remove all elements with value
"Dallas"
from
the list? If not, correct the code.
for
(
int
i =
0
; i < list.size(); i++)
list.remove(
"Dallas"
);
11.33
Explain why the following code displays
[1, 3]
rather than
[2, 3]
.
ArrayList<Integer> list =
new
ArrayList<>();
list.add(
1
);
list.add(
2
);
list.add(
3
);
list.remove(
1
);
System.out.println(list);
11.34
Explain why the following code is wrong.
ArrayList<Double> list =
new
ArrayList<>();
list.add(
1
);
Java provides the methods for creating a list from an array, for sorting a list, and
finding maximum and minimum element in a list, and for shuffling a list.
Key
Point
Often you need to create an array list from an array of objects or vice versa. You can write the
code using a loop to accomplish this, but an easy way is to use the methods in the Java API.
Here is an example to create an array list from an array:
array to array list
String[] array = {
"red"
,
"green", "blue"
};
ArrayList<String> list =
new
ArrayList<>(Arrays.asList(array));
The static method
asList
in the
Arrays
class returns a list that is passed to the
ArrayList
constructor for creating an
ArrayList
. Conversely, you can use the following code to create
an array of objects from an array list.
array list to array
String[] array1 =
new
String[list.size()];
list.toArray(array1);
Invoking
list.toArray(array1)
copies the contents from
list
to
array1
.
If the elements in a list are comparable such as integers, double, or strings, you can use the
static
sort
method in the
java.util.Collections
class to sort the elements. Here are
examples:
sort
a list
Integer[] array = {
3
,
5
,
95
,
4
,
15
,
34
,
3
,
6
,
5
};
ArrayList<Integer> list =
new
ArrayList<>(Arrays.asList(array));
java.util.Collections.sort(list);
System.out.println(list);
You can use the static
max
and
min
in the
java.util.Collections
class to return the
maximum and minimal element in a list. Here are examples:
max
and
min
methods
Integer[] array = {
3
,
5
,
95
,
4
,
15
,
34
,
3
,
6
,
5
};
ArrayList<Integer> list =
new
ArrayList<>(Arrays.asList(array));
System.out.println(java.util.Collections.max(list));
System.out.println(java.util.Collections.min(list));
Search WWH ::
Custom Search