Java Reference
In-Depth Information
18
19
// Display the distinct numbers
20
for ( int i = 0 ; i <
list.size()
; i++)
list.get(i)
21 System.out.print(
+ " " );
22 }
23 }
Enter numbers (input ends with 0):
The distinct numbers are: 1 2 3 6 4 5
1 2 3 2 1 6 3 4 5 4 5 1 2 3 0
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.
11.29
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.30
Identify the errors in the following code.
ArrayList<String> list = new ArrayList<String> ();
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 ));
11.31 Suppose the ArrayList list contains duplicate elements. Does the following code
correctly remove the element from the array list? If not, correct the code.
for ( int i = 0 ; i < list.size(); i++)
list.remove(element);
11.32 Explain why the following code displays [1, 3] rather than [2, 3] .
ArrayList<Integer> list = new ArrayList<Integer>();
list.add( 1 );
 
 
Search WWH ::




Custom Search