Java Reference
In-Depth Information
18
19
// Display the distinct numbers
20
for
(
int
i =
0
; i < list.size(); i++)
21 System.out.print(list.get(i) +
" "
);
22 }
23 }
Enter numbers (input ends with 0): 1 2 3 2 1 6 3 4 5 4 5 1 2 3 0
The distinct numbers are: 1 2 3 6 4 5
The program creates an
ArrayList
for
Integer
objects (line 6) and repeatedly reads a value in
the loop (lines 12-17). For each value, if it is not in the list (line 15), add it to the list (line 16). You
can rewrite this program using an array to store the elements rather than using an
ArrayList
.
However, it is simpler to implement this program using an
ArrayList
for two reasons.
First, the size of an
ArrayList
is flexible so you don't have to specify its size in
advance. When creating an array, its size must be specified.
■
■
Second,
ArrayList
contains many useful methods. For example, you can test
whether an element is in the list using the
contains
method. If you use an array,
you have to write additional code to implement this method.
You can traverse the elements in an array using a foreach loop. The elements in an array list
can also be traversed using a foreach loop using the following syntax:
for
(elementType element: arrayList) {
// Process the element
}
For example, you can replace the code in lines 20-21 using the following code:
for
(
int
number: list)
System.out.print(number +
“ “
);
11.30
✓
✓
How do you do the following?
Check
Point
a. Create an
ArrayList
for storing double values?
b. Append an object to a list?
c. Insert an object at the beginning of a list?
d. Find the number of objects in a list?
e. Remove a given object from a list?
f.
Remove the last object from the list?
g. Check whether a given object is in a list?
h. Retrieve an object at a specified index from a list?
11.31
Identify the errors in the following code.
ArrayList<String> list =
new
ArrayList<>();
list.add(
"Denver"
);
list.add(
"Austin"
);
list.add(
new
java.util.Date());
String city = list.get(
0
);
list.set(
3, "Dallas"
);
System.out.println(list.get(
3
));
Search WWH ::
Custom Search