Java Reference
In-Depth Information
You can make one important observation from the above output. You can print the list of all elements in an
ArrayList just by passing its reference to the System.out.println() method. The toString() method of the
ArrayList class returns a string that is a comma-separated string representation of its elements enclosed in
brackets ( [] ).
Like arrays, ArrayList uses zero-based indexing. That is, the first element of ArrayList has an index of zero.
You can get the element stored at any index by using the get() method.
// Get the element at the index 0 (the first element)
Integer firstId = ids.get(0);
// Get the element at the index 1 (the second element)
int secondId = ids.get(1); // Autounboxing is at play
You can check if the ArrayList contains an object using its contains() method.
Integer id20 = 20;
Integer id50 = 50;
// Add three objects to the arraylist
ids.add(10);
ids.add(20);
ids.add(30);
// Check if the array list contains id20 and id50
boolean found20 = ids.contains(id20); // found20 will be true
boolean found50 = ids.contains(id50); // found50 will be false
You can iterate through the elements of an ArrayList in one of the two ways: using a loop or using an iterator.
In this chapter, I will discuss how to iterate through elements of an ArrayList using a for loop. Please refer to the
chapter on Collections in the topic Beginning Java Language Features (ISBN 978-1-4302-6658-7) to learn how to iterate
through elements of an ArrayList (or any type of collection or set ) using an iterator. The following snippet of code
shows how to use a for loop to iterate through the elements of an ArrayList :
// Get the size of the ArrayList
int total = ids.size();
// Iterate through all elements
for (int i = 0; i < total; i++) {
int temp = ids.get(i);
// Do some processing...
}
If you want to iterate through all elements of the ArrayList without caring for their indexes, you can use the for -
each loop as shown:
// Iterate through all elements
for (int temp : ids) {
// Do some processing with temp...
}
Listing 15-3 illustrates the use of a for loop to iterate through elements of an ArrayList . It also shows you how to
remove an element from an ArrayList using the remove() method.
 
Search WWH ::




Custom Search