What is Collection in JAVA:
-It is a pre-defined structure that provides ready-made tools and libraries, and classes to help developers build applications efficiently.
Why do we need collections?
-Before collections, Java mainly used arrays to store multiple values. However, arrays have some limitations:
*Arrays have a fixed size
*They can store only the same type of elements(Homogeneous)
*Difficult to perform operations like insertion, deletion, and searching
*Memory waste for unused positions
Collections solve these problems by providing flexible and powerful data structures.
Java Collection Framework Hierarchy:
*The Collection interface is the root interface of the collections framework hierarchy.
*Java does not provide direct implementations of the Collection interface, but provides implementations of its subinterfaces like List, Set, and Queue.
- The framework includes other interfaces as well: Map and Iterator. These interfaces may also have subinterfaces.
Sub interfaces of collection:
- List Interface
- Set Interface
- Queue Interface
Map(Not a sub interface of collection)
What is List Interface:
A list interface is an ordered collection that allows us to store and access elements sequentially.
-In Java, we must import java.util.List package to use List.
// ArrayList implementation of List
ArrayList list = new ArrayList();
** Classes that implement List:**

Methods of List:
Methods Description
add() adds an element to a list
addAll() adds all elements of one list to another
get() helps to randomly access elements from lists
iterator() returns an iterator object that can be used to sequentially access elements of lists
set() changes elements of lists
remove() removes an element from the list
removeAll() removes all the elements from the list
clear() removes all the elements from the list (more efficient than removeAll())
size() returns the length of lists
toArray() converts a list into an array
contains() returns true if a list contains a specific element
Implementation of the List Interface
import java.util.List;
import java.util.ArrayList;
class Main {
public static void main(String[] args) {
// Creating list using the ArrayList class
List<Integer> numbers = new ArrayList<>();
// Add elements to the list
numbers.add(1);
numbers.add(2);
numbers.add(3);
System.out.println("List: " + numbers);
// Access element from the list
int number = numbers.get(2);
System.out.println("Accessed Element: " + number);
// Remove element from the list
int removedNumber = numbers.remove(1);
System.out.println("Removed Element: " + removedNumber);
}
}
List: [1, 2, 3]
Accessed Element: 3
Removed Element: 2
**2. What is set interface:**
-The Set interface stores unique elements and does not allow duplicates.
-Lists can include duplicate elements. However, sets cannot have duplicate elements.
-Elements in lists are stored in some order. However, elements in sets are stored in groups.

Top comments (0)