Java Reference
In-Depth Information
MyArrayList implements Iterable , the elements can be traversed using a for-each loop
(lines 35-36).
L ISTING 24.4
TestMyArrayList.java
1 public class TestMyArrayList {
2
public static void main(String[] args) {
3
// Create a list
4
MyList<String> list = new MyArrayList<String>();
create a list
5
6 // Add elements to the list
7 list.add( "America" ); // Add it to the list
8 System.out.println( "(1) " + list);
9
10 list.add(0, "Canada" ); // Add it to the beginning of the list
11 System.out.println( "(2) " + list);
12
13 list.add( "Russia" ); // Add it to the end of the list
14 System.out.println( "(3) " + list);
15
16 list.add( "France" ); // Add it to the end of the list
17 System.out.println( "(4) " + list);
18
19 list.add( 2 , "Germany" ); // Add it to the list at index 2
20 System.out.println( "(5) " + list);
21
22 list.add( 5 , "Norway" ); // Add it to the list at index 5
23 System.out.println( "(6) " + list);
24
25 // Remove elements from the list
26 list.remove( "Canada" ); // Same as list.remove(0) in this case
27 System.out.println( "(7) " + list);
28
29 list.remove( 2 ); // Remove the element at index 2
30 System.out.println( "(8) " + list);
31
32 list.remove(list.size() - 1 ); // Remove the last element
33 System.out.print( "(9) " + list + "\n(10) " );
34
35 for (String s: list)
36 System.out.print(s.toUpperCase() + " " );
37 }
38 }
add to list
remove from list
using iterator
(1) [America]
(2) [Canada, America]
(3) [Canada, America, Russia]
(4) [Canada, America, Russia, France]
(5) [Canada, America, Germany, Russia, France]
(6) [Canada, America, Germany, Russia, France, Norway]
(7) [America, Germany, Russia, France, Norway]
(8) [America, Germany, France, Norway]
(9) [America, Germany, France]
(10) AMERICA GERMANY FRANCE
24.5 What are the limitations of the array data type?
24.6 MyArrayList is implemented using an array, and an array is a fixed-size data struc-
ture. Why is MyArrayList considered a dynamic data structure?
Check
Point
 
 
Search WWH ::




Custom Search