Collection add() Method in Java with Examples

The add() method in Java is a part of the Collection interface, which is a member of the Java Collections Framework. This method is used to add an element to the collection. In this article, we will discuss the add() method in detail, along with some examples.

Syntax of add() Method:

The syntax of the add() method is as follows:

boolean add(E element)


Here, E represents the type of the element that we want to add to the collection. The add() method returns a boolean value, which is true if the element is successfully added to the collection, and false otherwise.

Examples:

Let’s see some examples to understand how the add() method works.

Example 1: Adding Elements to an ArrayList

import java.util.ArrayList;

public class Main {
public static void main(String[] args) {
ArrayList fruits = new ArrayList();
// Adding elements to the ArrayList
fruits.add("Apple");
fruits.add("Banana");
fruits.add("Mango");

// Printing the ArrayList
System.out.println(fruits);
}
}


Output:

[Apple, Banana, Mango]

In the above example, we have created an ArrayList named fruits. We have added three elements to this ArrayList using the add() method. Finally, we have printed the ArrayList using the println() method.

Example 2: Adding Elements to a HashSet

import java.util.HashSet;

public class Main {
public static void main(String[] args) {
HashSet countries = new HashSet();
// Adding elements to the HashSet
countries.add("India");
countries.add("USA");
countries.add("UK");

// Printing the HashSet
System.out.println(countries);
}
}


Output:

[India, USA, UK]


In the above example, we have created a HashSet named countries. We have added three elements to this HashSet using the add() method. Finally, we have printed the HashSet using the println() method.

Example 3: Adding Elements to a LinkedList

import java.util.LinkedList;

public class Main {
public static void main(String[] args) {
LinkedList names = new LinkedList();
// Adding elements to the LinkedList
names.add("John");
names.add("Mary");
names.add("Peter");

// Printing the LinkedList
System.out.println(names);
}
}


Output:

[John, Mary, Peter]

In the above example, we have created a LinkedList named names. We have added three elements to this LinkedList using the add() method. Finally, we have printed the LinkedList using the println() method.

Conclusion:

The add() method in Java is a very useful method that allows us to add elements to a collection. It is a part of the Collection interface, which is a member of the Java Collections Framework. We can use this method with different types of collections such as ArrayList, HashSet, and LinkedList, etc. By using the add() method, we can add elements to a collection easily and efficiently.