Java Reference
In-Depth Information
You can find out how many indices already have elements by using the method
size . If list is an ArrayList , list.size() returns the size of the ArrayList , which
is the number of elements stored in it. The indices of these elements go from 0 to
one less than list.size() .
size
The size Method
The method size returns the number of elements in an ArrayList .
EXAMPLE
for ( int index = 0; index < list.size(); index++)
System.out.println(list.get(index));
list is an ArrayList object.
TIP: Summary of Adding to an ArrayList
To place an element in an ArrayList position (at an ArrayList index) for the first
time, you usually use the method add . The simplest method named add has a single
parameter for the element to be added and adds elements at index positions 0 , 1 , 2 ,
and so forth, in that order.
You can add an element at an already occupied list position by using the two-parame-
ter version of add . When inserting into an ArrayList with this version of add , elements
at the specified index and higher are moved up one position to make room for the new
element. For example, suppose list is an ArrayList object with base type String that
has three elements already on its list. Consider the following method invocation:
add
list.add(1, "Amor");
Before there were elements at index positions 0 , 1 , and 2 . When this invocation of add
is executed, the element "Amor" is inserted at index 1 , and the elements at index posi-
tions 1 and 2 are moved to positions 2 and 3 .
You can also use the two-argument version of add to add an element at the first
unused position. If list has elements at index positions 0 , 1 , 2 , and 3 , then the follow-
ing is legal:
list.add(4, "Mucho Amor");
Your code can then go back and change any individual element, using set . However,
set can reset only the element at an index that already has an element.
The method size can be used to determine how many elements are stored in an
ArrayList .
Search WWH ::




Custom Search