How to initialize a list in java

A list is an ordered collection of objects. In Java, lists are represented by the List interface. The List interface provides a number of methods for manipulating lists, including adding and removing objects, retrieving objects, and sorting objects. In this article, we will cover how to initialize a list in java.

Create a list in java

To create a list, you first need to create an instance of the List interface. The following code creates a list of integers:

List list = new ArrayList();

The list variable is of type List, which means the list contains integers.

Add an object to a list in java

To add an object to a list, use the add() method. The following code adds the number 5 to the list:

list.add(5);


Remove an object from a list in java

To remove an object from a list, use the remove() method. The following code removes the number 5 from the list:

list.remove(5);

java.util.List Methods

java.util.List is an interface that represents a list of objects. It is a sub-interface of Collection. A list is an ordered collection of elements. The elements can be any type of object.

There are many methods in the List interface for performing various operations on lists. Some of the more commonly used methods are described below.

add()

The add() method adds an element to the end of the list.

remove()

The remove() method removes the first occurrence of a certain element from the list.

contains()

The contains() method determines whether a certain element is present in the list.

iterator()

The iterator() method returns an iterator over the elements in the list.

Also Read: Java-Syntax

Leave a Reply

Your email address will not be published. Required fields are marked *