Java Reference
In-Depth Information
When called with one argument, the
add
method inserts the element at the end of the
ArrayList
. Conversely, consider the syntax:
emps.add(0, new Employee())
.Thiscode
inserts the element at position 0 and shifts the rest of the elements one position to the
right. Similarly, the code
emps.remove(e)
will delete the first occurrence of the employee
e
from the
ArrayList
. Alternatively, the expression
emps.remove(0)
will delete the employee
at position 0. When an element is deleted, the other elements are shifted so that there is
no gap left by the deleted element.
Note that the
delete
method may sometimes seem ambiguous. Suppose that we have
an
ArrayList
of integers called
a
and write
a.delete(7)
. Will this delete the number at
position 7 or the first occurrence of the number 7 in the
ArrayList
? In order to answer this
important question, consider the following example.
import
java . util .
∗
;
public class
Test
{
public static void
main(String [] args)
{
ArrayList
<
Integer
>
a=
new
ArrayList
<
Integer
>
() ;
for
(
int
i=0;i
<
10; i++)
{
a.add(i+5);
a.remove(6);
System. out . println (a) ;
}
}
First, note that there is a
toString
method for the
ArrayList
class that prints the ele-
ments of the
ArrayList
. However, such a method does not exist for arrays. When executed,
the program will display.
[5, 6, 7, 8, 9, 10, 12, 13, 14]
Therefore, the element at position 6 is removed (remember that counting starts at 0).
Alternatively, if we want to remove the object 6, then we need to write the following code.
import
java . util .
∗
;
public class
Test
{
{
public static void
main(String [] args)
<
>
<
>
ArrayList
Integer
a=
new
ArrayList
Integer
() ;
for
(
int
i=0;i
<
10; i++)
{
a.add(i+5);
a.remove(
new
Integer(6));
System. out . println (a) ;
}
}
In other words, in this case we need to tell Java that we want to delete the object 6 and
not the element at position 6. In this case, the following output will be displayed.
[5, 7, 8, 9, 10, 11, 12, 13, 14]