Java ArrayList class
Java ArrayList class uses a dynamic array for storing the elements. It inherits AbstractList class and implements List interface.
The important points about Java ArrayList class are:
Hierarchy of ArrayList class
As shown in above diagram, Java ArrayList class extends AbstractList class which implements List interface. The List interface extends Collection and Iterable interfaces in hierarchical order.
ArrayList class declaration
Let's see the declaration for java.util.ArrayList class.
Constructors of Java ArrayList
Methods of Java ArrayList
Java Non-generic Vs Generic Collection
Java collection framework was non-generic before JDK 1.5. Since 1.5, it is generic.
Java new generic collection allows you to have only one type of object in collection. Now it is type safe so typecasting is not required at run time.
Let's see the old non-generic example of creating java collection.
Let's see the new generic example of creating java collection.
In generic collection, we specify the type in angular braces. Now ArrayList is forced to have only specified type of objects in it. If you try to add another type of object, it gives compile time error.
For more information of java generics, click here Java Generics Tutorial.
Java ArrayList ExampleTest it Now
Ravi Vijay Ravi Ajay
Two ways to iterate the elements of collection in java
There are two ways to traverse collection elements:
In the above example, we have seen traversing ArrayList by Iterator. Let's see the example to traverse ArrayList elements using for-each loop.
Iterating Collection through for-each loopTest it Now
Ravi Vijay Ravi Ajay
User-defined class objects in Java ArrayList
Let's see an example where we are storing Student class object in array list.Test it Now
101 Sonoo 23 102 Ravi 21 103 Hanumat 25
Example of addAll(Collection c) methodTest it Now
Ravi Vijay Ajay Sonoo Hanumat
Example of removeAll() methodTest it Now
iterating the elements after removing the elements of al2... Vijay Ajay
Example of retainAll() methodTest it Now
iterating the elements after retaining the elements of al2... Ravi
Java ArrayList Example: Book
Let's see an ArrayList example where we are adding books to list and printing all the books.Test it Now
101 Let us C Yashwant Kanetkar BPB 8 102 Data Communications & Networking Forouzan Mc Graw Hill 4 103 Operating System Galvin Wiley 6