List in Java

Introduction

Lists are ordered collections and part of the collection framework. All List classes and implementations use index-based operations namely searching elements, inserting elements, updating the list, deleting elements from the list as well as sorting in any order. Lists can have duplicate and null elements. Lists come under the java.util package and the implementations are ArrayList, LinkedList, Stack, and Vector. While the Vector class has lost significance in recent applications and programs, the ArrayList and LinkedList are one of the most used collections in all types of programs.

Declaration Syntax: public interface List <E> extends Collection <E>

Creating a New List

//This will create a new ArrayList of the String type
List <String> list = new ArrayList <String>();

//This will create a new ArrayList of the Integer type
List <Integer> list = new ArrayList <Integer>();

//This will create a new LinkedList of the String type
List <String> list = new LinkedList <String>();

//Creating a List of a user-defined data type
List <Student> list = new ArrayList <Student>();

Some List Methods

MethodDescription
Void add (int index, E element)Adding an element in the specified index.
Boolean add(E e)Add an element at the end of the list.
Void clear()This will remove all the current elements on the list. Therefore, the list will become empty.
Boolean equals (Object o)This is used to compare the Object with elements in the list.
Boolean isEmpty()Will return true if the list is empty.
E get(int index)This will return the element in the specified index.

 

Example

import java.util.*;
public class DemoList
{
public static void main (String args[])
{
List<String> list=new ArrayList<String>();
//Inserting elements in the List
list.add("Mango");
list.add("Apple");
list.add("Banana");
list.add("Grapes");
//Iterating the List element using for-each loop
for (String fruit : list)
System.out.println (fruit);
}
}

 

OUTPUT

Mango
Apple
Banana
Grapes

Leave a comment

This site uses Akismet to reduce spam. Learn how your comment data is processed.