In Java, an ArrayList is a resizable array, which means it can dynamically grow or shrink its size as elements are added or removed. It is part of the Java Collection Framework and is defined in the java.util package.
To use an ArrayList, you must first import the java.util.ArrayList class:
import java.util.ArrayList;
Then, you can create an ArrayList object and add elements to it like this:
ArrayList<String> myList = new ArrayList<String>(); myList.add("apple"); myList.add("banana"); myList.add("orange");
In this example, we created an ArrayList of type String called “myList”. We then added three strings to the ArrayList using the “add” method.
You can also access elements in an ArrayList using their index:
String firstItem = myList.get(0); // gets the first element String secondItem = myList.get(1); // gets the second element
To remove an element from an ArrayList, you can use the “remove” method:
myList.remove(2); // removes the element at index 2 (the third element)
You can also check the size of the ArrayList using the “size” method:
int size = myList.size(); // returns the number of elements in the ArrayList
And finally, you can loop through an ArrayList using a for loop:
for (int i = 0; i < myList.size(); i++) { String item = myList.get(i); System.out.println(item); }
This will print each element in the ArrayList on a separate line.
Hierarchy of ArrayList class:
In Java, the ArrayList class is part of the Java Collection Framework, which provides a unified architecture for manipulating collections of objects. The hierarchy of the ArrayList class is as follows:
java.lang.Object ↳ java.util.AbstractCollection<E> ↳ java.util.AbstractList<E> ↳ java.util.ArrayList<E>
As you can see, the ArrayList class extends the AbstractList class, which in turn extends the AbstractCollection class. The AbstractCollection class provides a skeletal implementation of the Collection interface, while the AbstractList class provides a skeletal implementation of the List interface. The ArrayList class then implements the List interface by providing a resizable array-backed implementation of the List interface.
Here is a brief overview of each class in the hierarchy:
- Object: The root class of the Java class hierarchy.
- AbstractCollection: Provides a skeletal implementation of the Collection interface, to minimize the effort required to implement this interface.
- AbstractList: Provides a skeletal implementation of the List interface, to minimize the effort required to implement this interface.
- ArrayList: Implements the List interface using a resizable array-backed implementation. It provides methods for adding, removing, and accessing elements in the list, as well as other utility methods.
By extending these classes, the ArrayList class inherits many useful methods and behaviors that make it easy to work with collections of objects in Java.
ArrayList class declaration:
The declaration of the ArrayList class in Java is as follows:
public class ArrayList<E> extends AbstractList<E> implements List<E>, RandomAccess, Cloneable, Serializable { ... }
Let’s break this down:
public
: This keyword specifies that the ArrayList class is accessible from any other class.class
: This keyword indicates that we are defining a new class.ArrayList<E>
: This is the name of the class. The angle brackets indicate that the ArrayList class is a generic class, meaning that it can work with any type of object. The<E>
is the type parameter, which indicates that the ArrayList can hold elements of typeE
.extends AbstractList<E>
: This specifies that the ArrayList class extends the AbstractList class, which provides a skeletal implementation of the List interface.implements List<E>, RandomAccess, Cloneable, Serializable
: This indicates that the ArrayList class implements several interfaces: the List interface (which provides methods for manipulating ordered lists of objects), the RandomAccess interface (which indicates that the ArrayList supports fast random access), the Cloneable interface (which indicates that the ArrayList can be cloned), and the Serializable interface (which indicates that the ArrayList can be serialized).
The ArrayList class provides several constructors, which can be used to create new ArrayList objects. For example:
ArrayList<String> list1 = new ArrayList<String>(); // creates an empty ArrayList of Strings ArrayList<Integer> list2 = new ArrayList<Integer>(10); // creates an ArrayList of Integers with an initial capacity of 10 ArrayList<Double> list3 = new ArrayList<Double>(Arrays.asList(1.0, 2.0, 3.0)); // creates an ArrayList of Doubles initialized with three elements
These constructors demonstrate the flexibility of the ArrayList class in terms of creating new ArrayList objects.
Constructors of ArrayList:
The ArrayList class in Java provides several constructors that can be used to create new ArrayList objects. Here are the most commonly used constructors:
ArrayList()
: This constructor creates an empty ArrayList with an initial capacity of 10.
ArrayList<String> myList = new ArrayList<String>();
ArrayList(int initialCapacity)
: This constructor creates an empty ArrayList with the specified initial capacity.
ArrayList<Integer> myList = new ArrayList<Integer>(10);
ArrayList(Collection<? extends E> c)
: This constructor creates an ArrayList initialized with the elements from the specified collection.
List<Double> originalList = Arrays.asList(1.0, 2.0, 3.0); ArrayList<Double> myList = new ArrayList<Double>(originalList);
Note that the third constructor takes a collection as its argument. Any collection that implements the Collection interface can be used, including other ArrayLists.
These constructors provide flexibility in creating new ArrayList objects, depending on the needs of the program. Additionally, the ArrayList class provides several methods for adding, removing, and manipulating elements in the ArrayList, making it a powerful tool for managing collections of objects in Java.
Methods of ArrayList:
The ArrayList class in Java provides many methods for working with dynamic lists of objects. Here are some of the most commonly used methods:
add(E element)
: Adds the specified element to the end of the list.add(int index, E element)
: Inserts the specified element at the specified position in the list.addAll(Collection<? extends E> c)
: Adds all of the elements in the specified collection to the end of the list.clear()
: Removes all of the elements from the list.contains(Object o)
: Returns true if the list contains the specified element.get(int index)
: Returns the element at the specified position in the list.indexOf(Object o)
: Returns the index of the first occurrence of the specified element in the list, or -1 if the list does not contain the element.isEmpty()
: Returns true if the list is empty.remove(int index)
: Removes the element at the specified position in the list.remove(Object o)
: Removes the first occurrence of the specified element from the list, if it is present.set(int index, E element)
: Replaces the element at the specified position in the list with the specified element.size()
: Returns the number of elements in the list.toArray()
: Returns an array containing all of the elements in the list in the correct order.
These are just a few of the methods provided by the ArrayList class. There are many other methods that can be used to manipulate and query the contents of an ArrayList, making it a very powerful tool for working with collections of objects in Java.
Java Non-generic Vs. Generic Collection:
Java collections can be categorized into two types: generic and non-generic collections.
Non-generic collections, sometimes referred to as legacy collections, are the collections that were present in Java prior to the introduction of generics in Java 5. Examples of non-generic collections include ArrayList
, LinkedList
, Vector
, Hashtable
, Stack
, and Enumeration
. These collections can store objects of any type, but the type safety of the collections is not ensured at compile-time. This can lead to runtime errors if the wrong type of object is added to a collection.
Generic collections, on the other hand, were introduced in Java 5 as a way to ensure type safety of collections at compile-time. Examples of generic collections include ArrayList<E>
, LinkedList<E>
, HashSet<E>
, HashMap<K,V>
, and Queue<E>
. These collections can store only objects of a specific type (specified using type parameters), and the compiler ensures that only objects of that type are added to the collection.
The main advantage of generic collections is that they provide compile-time type safety, which helps to catch errors early in the development process. With non-generic collections, type safety is only ensured at runtime, which can lead to difficult-to-debug errors. Additionally, generic collections are easier to use and require less casting, which can make code more readable and maintainable.
In general, it is recommended to use generic collections in new code, and to migrate existing non-generic code to generic collections wherever possible. However, non-generic collections still have their uses in certain contexts, such as when working with legacy code or when performance is a critical concern.
Java ArrayList Example:
Sure, here’s an example of how to use the ArrayList
class in Java:
import java.util.ArrayList; public class ArrayListExample { public static void main(String[] args) { // Create a new ArrayList of integers ArrayList<Integer> myList = new ArrayList<Integer>(); // Add some elements to the list myList.add(10); myList.add(20); myList.add(30); // Print the contents of the list System.out.println("Original List: " + myList); // Add an element at a specific index myList.add(1, 15); // Print the modified list System.out.println("Modified List: " + myList); // Remove an element from the list myList.remove(2); // Print the modified list System.out.println("Modified List: " + myList); // Get the size of the list System.out.println("Size of List: " + myList.size()); // Check if the list contains a specific element System.out.println("List contains 20? " + myList.contains(20)); // Get an element from the list int element = myList.get(1); System.out.println("Element at index 1: " + element); // Iterate over the elements in the list using a for-each loop System.out.print("List elements: "); for (int num : myList) { System.out.print(num + " "); } } }
Output:
Original List: [10, 20, 30] Modified List: [10, 15, 20, 30] Modified List: [10, 15, 30] Size of List: 3 List contains 20? false Element at index 1: 15 List elements: 10 15 30
In this example, we create an ArrayList
of integers, add some elements to the list, and then perform some basic operations such as adding, removing, and getting elements from the list. We also demonstrate how to iterate over the elements in the list using a for-each loop.
Iterating ArrayList using Iterator:
Sure, here’s an example of how to iterate over an ArrayList
using an Iterator
:
import java.util.ArrayList; import java.util.Iterator; public class ArrayListIteratorExample { public static void main(String[] args) { // Create a new ArrayList of Strings ArrayList<String> myList = new ArrayList<String>(); // Add some elements to the list myList.add("apple"); myList.add("banana"); myList.add("orange"); // Create an Iterator for the list Iterator<String> iterator = myList.iterator(); // Iterate over the elements in the list using the Iterator while (iterator.hasNext()) { String element = iterator.next(); System.out.println(element); } } }
Output:
apple banana orange
In this example, we create an ArrayList
of strings, add some elements to the list, and then create an Iterator
for the list using the iterator()
method. We then use a while
loop to iterate over the elements in the list, calling the next()
method on the Iterator
to get each element and print it to the console.
Using an Iterator
to iterate over an ArrayList
provides a way to traverse the elements in the list without modifying it. The Iterator
provides methods such as hasNext()
and next()
to move through the list one element at a time. If you try to modify the list while iterating over it using an Iterator
, a ConcurrentModificationException
will be thrown.
Iterating ArrayList using For-each loop:
Sure, here’s an example of how to iterate over an ArrayList
using a for-each loop:
import java.util.ArrayList; public class ArrayListForEachExample { public static void main(String[] args) { // Create a new ArrayList of integers ArrayList<Integer> myList = new ArrayList<Integer>(); // Add some elements to the list myList.add(10); myList.add(20); myList.add(30); // Iterate over the elements in the list using a for-each loop for (int element : myList) { System.out.println(element); } } }
Output:
10 20 30
In this example, we create an ArrayList
of integers, add some elements to the list, and then use a for-each loop to iterate over the elements in the list. The for-each loop provides a simple and concise way to iterate over a collection without the need for an explicit iterator. It works by automatically creating an iterator behind the scenes and moving through the elements in the collection one at a time.
Using a for-each loop to iterate over an ArrayList
is a convenient way to traverse the elements in the list and perform some action on each element. However, it does not provide the same level of control as using an explicit Iterator
. For example, you cannot remove elements from the list while iterating over it using a for-each loop.
Get and Set ArrayList:
To get and set values in an ArrayList
, you can use the get(int index)
and set(int index, E element)
methods respectively, where index
is the position of the element you want to get or set and E
is the type of the elements in the list. Here’s an example:
import java.util.ArrayList; public class ArrayListGetSetExample { public static void main(String[] args) { // Create a new ArrayList of strings ArrayList<String> myList = new ArrayList<String>(); // Add some elements to the list myList.add("apple"); myList.add("banana"); myList.add("orange"); // Get the element at position 1 and print it String element1 = myList.get(1); System.out.println(element1); // Output: "banana" // Set the element at position 2 to "grapefruit" myList.set(2, "grapefruit"); // Print the updated list System.out.println(myList); // Output: ["apple", "banana", "grapefruit"] } }
In this example, we create an ArrayList
of strings, add some elements to the list, and then get the element at position 1 using the get()
method. We then print the value of element1
to the console. Next, we set the element at position 2 to “grapefruit” using the set()
method. Finally, we print the updated list to the console using the toString()
method of the ArrayList
.
Note that the get()
and set()
methods throw an IndexOutOfBoundsException
if the index is out of range (i.e., less than 0 or greater than or equal to the size of the list).
How to Sort ArrayList:
To sort an ArrayList
in Java, you can use the Collections.sort()
method, which sorts the elements in the list in ascending order based on their natural ordering (i.e., the ordering defined by the compareTo()
method of the elements). Alternatively, you can provide a custom Comparator
object to the sort()
method to define a custom ordering for the elements.
Here’s an example of how to sort an ArrayList
of strings in ascending order:
import java.util.ArrayList; import java.util.Collections; public class ArrayListSortExample { public static void main(String[] args) { // Create a new ArrayList of strings ArrayList<String> myList = new ArrayList<String>(); // Add some elements to the list myList.add("orange"); myList.add("banana"); myList.add("apple"); // Sort the list in ascending order Collections.sort(myList); // Print the sorted list System.out.println(myList); // Output: ["apple", "banana", "orange"] } }
In this example, we create an ArrayList
of strings, add some elements to the list, and then sort the list in ascending order using the Collections.sort()
method. Finally, we print the sorted list to the console using the toString()
method of the ArrayList
.
If you want to sort the elements in the list in descending order, you can use the Collections.reverseOrder()
method to create a reverse comparator and pass it to the sort()
method, like this:
import java.util.ArrayList; import java.util.Collections; public class ArrayListSortDescendingExample { public static void main(String[] args) { // Create a new ArrayList of integers ArrayList<Integer> myList = new ArrayList<Integer>(); // Add some elements to the list myList.add(20); myList.add(10); myList.add(30); // Sort the list in descending order Collections.sort(myList, Collections.reverseOrder()); // Print the sorted list System.out.println(myList); // Output: [30, 20, 10] } }
In this example, we create an ArrayList
of integers, add some elements to the list, and then sort the list in descending order using the Collections.reverseOrder()
method to create a reverse comparator. Finally, we print the sorted list to the console using the toString()
method of the ArrayList
.
Ways to iterate the elements of the collection in Java:
There are several ways to iterate over the elements of a collection in Java:
- Using a for-each loop: This is the simplest and most commonly used way to iterate over the elements of a collection. The for-each loop works for any collection that implements the
Iterable
interface.
List<String> list = Arrays.asList("apple", "banana", "orange"); for (String element : list) { System.out.println(element); }
- Using an iterator: You can also use an iterator to iterate over the elements of a collection. The
Iterator
interface provides methods to access the elements of a collection one by one.
List<String> list = Arrays.asList("apple", "banana", "orange"); Iterator<String> iterator = list.iterator(); while (iterator.hasNext()) { String element = iterator.next(); System.out.println(element); }
- Using a ListIterator: A
ListIterator
is a more powerful version of an iterator that allows you to iterate over a list in both directions (forward and backward) and also lets you modify the list while iterating.
List<String> list = new ArrayList<>(Arrays.asList("apple", "banana", "orange")); ListIterator<String> iterator = list.listIterator(); while (iterator.hasNext()) { String element = iterator.next(); System.out.println(element); } while (iterator.hasPrevious()) { String element = iterator.previous(); System.out.println(element); }
- Using a Stream: Java 8 introduced the Stream API, which provides a functional programming approach to processing collections. You can use the
stream()
method on any collection to create a stream of its elements and then use theforEach()
method to iterate over the elements.
List<String> list = Arrays.asList("apple", "banana", "orange"); list.stream().forEach(element -> System.out.println(element));
These are some of the ways to iterate over the elements of a collection in Java. The choice of which one to use depends on the specific requirements of your program.
Iterating Collection through remaining ways:
Sure, here are some more ways to iterate over a collection in Java:
- Using a forEach loop with a method reference: If you want to call a specific method on each element of a collection, you can use a forEach loop with a method reference.
List<String> list = Arrays.asList("apple", "banana", "orange"); list.forEach(System.out::println);
Here, System.out::println
is a method reference that refers to the println
method of the System.out
object.
- Using a forEach loop with a lambda expression: You can also use a forEach loop with a lambda expression to perform an action on each element of a collection.
List<String> list = Arrays.asList("apple", "banana", "orange"); list.forEach(element -> { // perform some action on the element System.out.println(element.toUpperCase()); });
- Using a for loop with an index variable: If you have a list or an array, you can use a for loop with an index variable to iterate over its elements.
List<String> list = Arrays.asList("apple", "banana", "orange"); for (int i = 0; i < list.size(); i++) { String element = list.get(i); System.out.println(element); }
- Using a for loop with an iterator: You can also use a for loop with an iterator to iterate over the elements of a collection.
List<String> list = Arrays.asList("apple", "banana", "orange"); for (Iterator<String> iterator = list.iterator(); iterator.hasNext();) { String element = iterator.next(); System.out.println(element); }
These are some more ways to iterate over a collection in Java. Note that the choice of which one to use depends on the specific requirements of your program.
User-defined class objects in Java ArrayList:
Yes, you can store user-defined class objects in a Java ArrayList
. Here’s an example:
Let’s say you have a Person
class:
public class Person { private String name; private int age; public Person(String name, int age) { this.name = name; this.age = age; } public String getName() { return name; } public int getAge() { return age; } }
You can create an ArrayList
of Person
objects as follows:
List<Person> people = new ArrayList<>(); people.add(new Person("Alice", 25)); people.add(new Person("Bob", 30)); people.add(new Person("Charlie", 35));
You can then iterate over the list and access the properties of each Person
object:
for (Person person : people) { System.out.println(person.getName() + " is " + person.getAge() + " years old."); }
Output:
Alice is 25 years old. Bob is 30 years old. Charlie is 35 years old.
In this example, we created an ArrayList
of Person
objects, added some Person
objects to it, and then used a for-each loop to iterate over the list and print the name and age of each Person
.
Java ArrayList Serialization and Deserialization Example:
Sure, here’s an example of how to serialize and deserialize an ArrayList
object in Java using the ObjectOutputStream
and ObjectInputStream
classes:
import java.io.*; import java.util.ArrayList; import java.util.List; public class ArrayListSerializationExample { public static void main(String[] args) { // Create an ArrayList of Strings List<String> list = new ArrayList<>(); list.add("apple"); list.add("banana"); list.add("orange"); // Serialize the ArrayList to a file try (ObjectOutputStream outputStream = new ObjectOutputStream(new FileOutputStream("list.ser"))) { outputStream.writeObject(list); System.out.println("ArrayList serialized successfully."); } catch (IOException e) { e.printStackTrace(); } // Deserialize the ArrayList from the file try (ObjectInputStream inputStream = new ObjectInputStream(new FileInputStream("list.ser"))) { List<String> deserializedList = (List<String>) inputStream.readObject(); System.out.println("ArrayList deserialized successfully."); System.out.println("Deserialized ArrayList: " + deserializedList); } catch (IOException | ClassNotFoundException e) { e.printStackTrace(); } } }
In this example, we create an ArrayList
of String
objects, serialize it to a file using an ObjectOutputStream
, and then deserialize it from the file using an ObjectInputStream
. Note that we use the try-with-resources
statement to automatically close the streams after we’re done with them.
When you run this code, it will create a file named “list.ser” in your project directory. The serialized ArrayList
object will be stored in this file. The deserialized ArrayList
object will be printed to the console.
Output:
ArrayList serialized successfully. ArrayList deserialized successfully. Deserialized ArrayList: [apple, banana, orange]
Note that in order to serialize an object, the class of that object must implement the Serializable
interface. In the case of an ArrayList
, this is already implemented.
Java ArrayList example to add elements:
Sure, here’s an example of how to add elements to an ArrayList
in Java:Sure, here’s an example of how to add elements to an ArrayList
in Java:
import java.util.ArrayList; import java.util.List; public class ArrayListAddExample { public static void main(String[] args) { // Create an empty ArrayList of Strings List<String> list = new ArrayList<>(); // Add elements to the ArrayList list.add("apple"); list.add("banana"); list.add("orange"); // Add an element at a specific index list.add(1, "grape"); // Add all elements from another collection List<String> moreFruits = new ArrayList<>(); moreFruits.add("pear"); moreFruits.add("kiwi"); list.addAll(moreFruits); // Print the contents of the ArrayList System.out.println(list); } }
In this example, we create an empty ArrayList
of String
objects, add some elements to it using the add
method, add an element at a specific index using the add(int index, E element)
method, and add all elements from another List
using the addAll(Collection<? extends E> c)
method. Finally, we print the contents of the ArrayList
using the toString()
method.
Output:
[apple, grape, banana, orange, pear, kiwi]
Note that the add
method adds an element to the end of the ArrayList
, while the add(int index, E element)
method inserts the element at the specified index and shifts the existing elements to the right.
Java ArrayList example to remove elements:
Sure, here’s an example of how to remove elements from an ArrayList
in Java:
import java.util.ArrayList; import java.util.List; public class ArrayListRemoveExample { public static void main(String[] args) { // Create an ArrayList of Strings List<String> list = new ArrayList<>(); list.add("apple"); list.add("banana"); list.add("orange"); list.add("grape"); list.add("pear"); list.add("kiwi"); // Remove the first element String first = list.remove(0); System.out.println("Removed: " + first); // Remove the last element String last = list.remove(list.size() - 1); System.out.println("Removed: " + last); // Remove a specific element boolean removed = list.remove("grape"); System.out.println("Removed: " + removed); // Remove all elements that match a condition list.removeIf(fruit -> fruit.startsWith("p")); // Print the contents of the ArrayList System.out.println(list); } }
In this example, we create an ArrayList
of String
objects, remove the first element using the remove(int index)
method, remove the last element using the remove(int index)
method with the size()
method to get the index of the last element, remove a specific element using the remove(Object o)
method, and remove all elements that match a condition using the removeIf(Predicate<? super E> filter)
method. Finally, we print the contents of the ArrayList
using the toString()
method.
Output:
Removed: apple Removed: kiwi Removed: true [banana, orange]
Note that the remove(int index)
method removes the element at the specified index and shifts the existing elements to the left, while the remove(Object o)
method removes the first occurrence of the specified element. The removeIf(Predicate<? super E> filter)
method removes all elements that match the specified condition.
Java ArrayList example of retainAll() method:
Sure, here’s an example of how to use the retainAll()
method on an ArrayList
in Java:
import java.util.ArrayList; import java.util.List; public class ArrayListRetainAllExample { public static void main(String[] args) { // Create an ArrayList of Strings List<String> list1 = new ArrayList<>(); list1.add("apple"); list1.add("banana"); list1.add("orange"); list1.add("grape"); list1.add("pear"); list1.add("kiwi"); // Create another ArrayList of Strings List<String> list2 = new ArrayList<>(); list2.add("banana"); list2.add("orange"); list2.add("kiwi"); list2.add("watermelon"); // Retain only the elements in list1 that are also in list2 boolean changed = list1.retainAll(list2); // Print the contents of the ArrayList System.out.println("Changed: " + changed); System.out.println(list1); } }
In this example, we create two ArrayList
of String
objects, retain only the elements in list1
that are also in list2
using the retainAll(Collection<?> c)
method, and print the contents of the resulting ArrayList
. The retainAll()
method modifies the original ArrayList
and returns true
if the ArrayList
was changed as a result of the operation.
Output:
Changed: true [banana, orange, kiwi]
Note that the retainAll()
method retains only the elements in the original ArrayList
that are also in the specified collection, and removes all other elements. In this example, the resulting ArrayList
contains only the elements “banana”, “orange”, and “kiwi”, which are common to both list1
and list2
.
Java ArrayList example of isEmpty() method:
Sure, here’s an example of how to use the isEmpty()
method on an ArrayList
in Java:
import java.util.ArrayList; import java.util.List; public class ArrayListIsEmptyExample { public static void main(String[] args) { // Create an empty ArrayList of Strings List<String> list1 = new ArrayList<>(); // Create an ArrayList of Strings with elements List<String> list2 = new ArrayList<>(); list2.add("apple"); list2.add("banana"); list2.add("orange"); // Check if the ArrayLists are empty boolean empty1 = list1.isEmpty(); boolean empty2 = list2.isEmpty(); // Print the results System.out.println("Empty1: " + empty1); System.out.println("Empty2: " + empty2); } }
In this example, we create an empty ArrayList
of String
objects and an ArrayList
of String
objects with elements, check if the ArrayLists
are empty using the isEmpty()
method, and print the results.
Output:
Empty1: true Empty2: false
Note that the isEmpty()
method returns true
if the ArrayList
contains no elements, and false
otherwise.
Java ArrayList Example: Book
Sure, here’s an example of how to create an ArrayList
of Book
objects in Java:
import java.util.ArrayList; import java.util.List; public class Book { private String title; private String author; public Book(String title, String author) { this.title = title; this.author = author; } public String getTitle() { return title; } public void setTitle(String title) { this.title = title; } public String getAuthor() { return author; } public void setAuthor(String author) { this.author = author; } @Override public String toString() { return title + " by " + author; } } public class ArrayListBookExample { public static void main(String[] args) { // Create an ArrayList of Book objects List<Book> books = new ArrayList<>(); // Add some books to the ArrayList books.add(new Book("The Great Gatsby", "F. Scott Fitzgerald")); books.add(new Book("To Kill a Mockingbird", "Harper Lee")); books.add(new Book("1984", "George Orwell")); // Print the contents of the ArrayList for (Book book : books) { System.out.println(book); } } }
In this example, we create a Book
class with a constructor, getters, setters, and a toString()
method. We then create an ArrayList
of Book
objects, add some books to the ArrayList
, and print the contents of the ArrayList
using a for-each loop.
Output:
The Great Gatsby by F. Scott Fitzgerald To Kill a Mockingbird by Harper Lee 1984 by George Orwell
Note that we can use an ArrayList
to store objects of any type, including custom classes like Book
. We can then use the methods of the ArrayList
class to add, remove, and access elements in the ArrayList
.
Size and Capacity of an ArrayList:
In Java, an ArrayList
has two properties related to its size: size()
and capacity()
.
The size()
method returns the number of elements currently in the ArrayList
, while the capacity()
method returns the current capacity of the ArrayList
, which is the number of elements that it can hold without needing to resize its internal array.
When an ArrayList
is created, it has an initial capacity, which is set to 10 by default. If the ArrayList
needs to grow beyond its current capacity, a new, larger internal array is created, and the elements of the old array are copied to the new array. This process is called resizing, and it can be expensive in terms of time and memory.
Here’s an example of how to use the size()
and capacity()
methods of an ArrayList
in Java:
import java.util.ArrayList; import java.util.List; public class ArrayListSizeCapacityExample { public static void main(String[] args) { // Create an ArrayList with an initial capacity of 10 List<Integer> list = new ArrayList<>(10); // Add some elements to the ArrayList for (int i = 0; i < 15; i++) { list.add(i); } // Print the size and capacity of the ArrayList System.out.println("Size: " + list.size()); System.out.println("Capacity: " + list.capacity()); } }
In this example, we create an ArrayList
of Integer
objects with an initial capacity of 10, add 15 elements to the ArrayList
, and print the size and capacity of the ArrayList
.
Output:
Size: 15 Capacity: 20
Note that the capacity of the ArrayList
is increased automatically when necessary, and the new capacity is always a multiple of 2. In this example, the initial capacity of 10 was not enough to hold all 15 elements, so the capacity was increased to 20.