×

Collections in Java

Collection framework is one of Java's most powerful subsystems. It is a set of classes and interfaces that is all-the-rage technology for superintending objects and a group of objects. In simple terms; "A collection framework is a container which allows grouping of a number of elements together". It is symbiotic in sorting data and processing it efficiently. Collection Frameworks work as libraries. Collection framework has:
  • Interfaces
  • Classes to implement the interface.
  • Algorithms.

How is Collection Framework different from arrays?

Unlike array;
  • The size of the collection need not to be declared at the time of instantiation. They can resize themselves with respect to objects automatically.
  • Collections cannot hold basic data types.

Operations that can be performed on collection

A list of operations that can be performed on any collection:
  • Addition of new object.
  • Deletion of an existing object.
  • Traversing the objects.
  • Retrieving desired objects.
  • Deleting desired objects.
  • Searching a particular object.

Collection-Interface Hierarchy

Interfaces in Collection Framework

Collection interfaces determine the fundamental nature of collection classes. There are various interfaces in the collection framework. They are listed below. 1. Collection? It is a generic interface at the top of the collection hierarchy. Every class needs to implement this interface. It enables the users to work with a group of objects. Collection implements the Iterable interface. The general declaration is: interface CollectionE specifies the type of objects that the collection will hold. 2. Queue ? It extends the Collection interface and declares the behavior of a queue. Queue is a data structure that follows the first in first out (FIFO) principle. It is a generic interface. The declaration of queue is: interface QueueE specifies the type of objects that the queue will hold. 3. Dequeue? It extends the Queue interface. Dequeue is a double-ended queue in which the insertion and deletion of elements are possible from both the ends of queue. It is a generic interface with the declaration as interface Dequeue.E specifies the type of objects that dequeue will hold. 4. List ? It extends the collection interface and declares a structure to store a sequence of the element. Elements can be accessed, inserted, deleted by specifying their position in the list. It is a generic interface with declaration as interface List.E specifies the type of objects that the list will hold. 5. Set ? It extends the collection interface and declares a set. The set stores the element such that there is no repetition. It is a generic interface with declaration as interface Set.E specifies the type of objects that the set will hold. 6. SortedSet? It extends the set and declares the behavior stored in a set in ascending order. It is a generic interface with declaration as interface SortedSet.E specifies the type of objects that the set will hold. 7. NavigableSet? It extends the SortedSet interface and declared the behavior of elements such that element with the closest match to a given value is retrieved. It is a generic interface with declaration as interface NavigableSet.E specifies the type of objects that the set will hold.

Classes in Collection

There are various classes in the Collection. Some classes provide full implementation while the rest provide a skeletal structure. The various classes are discussed below:
  1. AbstractCollection: This class implements most of the interfaces which are defined in the collection.
  2. AbstractList: This class inherits the AbstractCollection class and implements most of the interfaces in the List Interface.
  3. AbstractQueue: This class inherits the AbstractCollection class and implements most of the interfaces in the Queue Interface.
  4. AbstractSequentialList: This class inherits the AbstractList class for use in the files which uses sequential access. Sequential access is the one in which each word is iterated one by one.
  5. LinkedList: This class inherits the AbstractSequentialList class and implements linked lists.
  6. ArrayList: This class inherits the AbstractList class and implements a dynamic array. A dynamic array is the one in which the size is declared at run time.
  7. ArrayDeque: This class inherits the AbstractCollection class and implements the dequeue interface. It implements a double-ended queue dynamic in nature.
  8. AbstractSet: This class inherits the AbstractCollection class and implements most of the interfaces in the list interface.
  9. EnumSet: This class inherits the AbstractSet class and uses it with the enum elements.
  10. HashSet: This class inherits the AbstractSet class and uses it with the hash table.
  11. LinkedHashSet: This class inherits the HashSet class and allows iterations in the order of insertion.
  12. PriorityQueue: This class inherits the AbstractQueue class and uses it in the making of priority queues.
  13. TreeSet: This class inherits the AbstractSet class and uses to make a sorted set in the tree.

Algorithm in Collection

The collection defines several algorithms that can be used with the collection class.

Useful methods of collection interface are as follows:

add():  The add() method inserts a new element into the collection and returns whether it was successful.

The method signature is

boolean add(E element)

The collection uses generics “E for Elements”.  It means the generic type that was used to create the collection.

Example :

import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set;

public class ListExample {
public static void main(String[] args)
{
List<String> countries = new ArrayList<>(); // Creating list of
System.out.println(countries.add("INDIA")); // will return true.
Set<String> countries1 = new HashSet<>();
System.out.println(countries1.add("INDIA")); // will return true
System.out.println(countries1.add("INDIA")); // will return false (set does not allows duplicate)
}
}

Output:

true
true
false

remove(): The remove() method removes a single matching value in the collection and returns whether it was successful.

The method signature is

boolean remove(Object object)

Example :

import java.util.ArrayList;
import java.util.List;
public class RemoveExample {
public static void main(String[] args) {
List<String> countries = new ArrayList<>(); // creating List of countries
countries.add("INDIA"); // adding INDIA will return true // [INDIA]
countries.add("INDIA"); // adding INDIA again will return true //[INDIA,INDIA]
System.out.println(countries .remove("CHINA")); // removing CHINA and will return false
System.out.println( countries .remove("INDIA")); // removing INDIA and will return true
System.out.println(countries); // will print list of countries ([INDIA])
}
}

Output:

false
true
[INDIA]

isEmpty() : Checks if the collection have elements:

signature:   boolean isEmpty()

Example:

import java.util.ArrayList;
import java.util.List;
public class IsEmptyExample {
public static void main(String[] args) {
List<String> countries = new ArrayList<>(); 
System.out.println(countries.isEmpty());  // returns false
countries.add("INDIA");
System.out.println(countries.isEmpty());  // returns true
}
}

Output:

true
false

size():  looks  how many elements are in the Collection.

Signature is :   int size()

Example:

import java.util.ArrayList;
import java.util.List;
public class SizeExample {
public static void main(String[] args) {
List<String> countries = new ArrayList<>(); 
System.out.println(countries.size()); // returns 0
countries.add("INDIA");
System.out.println(countries.size()); // returns 1
}
}

Output:

0
1

clear():  The clear() method provides an easy way to discard all elements of the Collection. The method signature is

void clear()

Example:

import java.util.ArrayList;
import java.util.List;
public class ClearExample {
public static void main(String[] args) {
List<String> countries = new ArrayList<>(); 
countries.add("INDIA");
countries.add("CHINA");
System.out.println(countries.size());  // returns 2
countries.clear();  // []
System.out.println(countries.size());  // return 0
}
}

Output:

2
0

contains(): The contains() method checks if a certain value is in the Collection.

The method signature is

boolean contains(Object object)

Example:

import java.util.ArrayList;
import java.util.List;
public class ListExample {
public static void main(String[] args) {
List<String> countries = new ArrayList<>(); 
countries.add("INDIA");
System.out.println(countries.contains("INDIA")); // returns true
System.out.println(countries.contains("CHINA"));// returns false
}
}

Output:

true
false

Related Topics

Java Math expm1() Method

The expm1() method of Math class returns ex-1 where e represents Euler’s number. Syntax: public static double expm1(double x) Parameters: The parameter ‘x’ represents the exponent to raise e in the calculation of ex-1. Return...

2 minutes read.

Java String indexOf() method

Java String indexOf() method returns index of a given character or substring present in a String. Methods Description int indexOf(int ch)     It returns index position for the given char value.int indexOf(int ch,...

2 minutes read.

Features of Java

The objective of the Java programming language is to provide portability, security, and simplicity. In spite of this, Java has a number of features that makes it a popular language...

5 minutes read.

Davis Staircase Problem in Java

Davis has several stairs in his home and prefers to ascend one, two, or three steps at a time. As a highly clever youngster, he thinks about how many ways...

3 minutes read.

Various operations on the Queue using Stack in Java

The Java Collections Framework's core data structures are the Stack and Queue. They are used to store and retrieve identical data in a presentation sequence. These two linear data structures...

7 minutes read.

How to download and install Eclipse in Windows?

Download and Install Eclipse on Windows Eclipse is an open source IDE (Integrated Development Environment) which is used to help the programmers to provide a platform to write and run the...

1 minute read.

Automorphic Number Program in Java

We will learn about automorphic numbers through examples in this article, and we'll also make Java programmes that can determine whether a specific number was automorphic or not. What is an...

3 minutes read.

Java Snippets

The term "snippet" refers to a section of code that addresses numerous issues with just a few lines of code. Decreases the number of lines of code and improves programmer...

3 minutes read.

Java Command Line Arguments

Java command line arguments Command line argument is an input or argument to the program when you run the program. In Java, we can take the inputs from the console, and...

2 minutes read.

Advanced Java skills

These were some of the contemporary talents that a Java developer should master in efforts to progress in the era of science in 2022. A database such as MySQL, a...

4 minutes read.

Bounded buffer problem in Java

The Bounded buffer Problem can also be called a Producer consumer problem. The problem covers two processes—the producer and the consumer—that share a single, fixed-size buffer that serves as a...

4 minutes read.

Java Throw and Throws Keyword

Exceptions in Java enable us to construct high-quality programs where faults are checked at compile time rather than run time and where we may define unique exceptions that make code...

6 minutes read.

Java array list remove time complexity

Java: We know that java is one of the programming languages. The main feature of java which is not in C or object oriented programming language is platform independence. Not only the...

7 minutes read.

Java Math nextAfter() Method

The nextAfter() method of Math class returns the floating-point value adjacent to the first argument in direction of the second argument. Syntax: public static double nextAfter (double start, double direction)public static float...

2 minutes read.

Difference Between replace() and replaceall() in Java

In this article, you will be acknowledged about the replace() and replaceall() methods in java. Also, most importantly you will be acknowledged the differences between them along with the example...

4 minutes read.

Creating API Document Javadoc tool

The JavaDoc utility is a document generator tool written in Java that generates standard documentation in HTML format. It parses declarations and documentation in a source file collection that describes...

3 minutes read.

Two Decimal Places Java

When a double data type is used in Java before a variable, this indicates 15 digits after decimal point. However, there are situations when we only require 2 decimal places...

4 minutes read.

Creating a Custom Generic Class in Java

To indicate parameter types when creating generic classes, we utilize the <> symbol. The syntax used to generate objects of a generic class is as follows. // To create an instance...

4 minutes read.

Types of Logical Operators in Java

In this tutorial, we are going to study logical operators. A logical operator is an operator that accomplishes a logical operation that is to connect two or more operations. These...

5 minutes read.

Jagged Array in Java

Prerequisite We must first understand what Arrays are and Multi-dimensional Arrays are before we can learn about Jagged arrays. Java Arrays: A collection of data types that are similar is called an...

5 minutes read.