×

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

Knapsack problem in Java

We have a collection of items in the knapsack problem. Every object has a weight and a value. These things should go in a knapsack. But there is a weight...

3 minutes read.

Java Variable Declaration

In this article, you will be acknowledged about java variable declaration. You will be able to learn and interpret about declaring a variable in Java. Variable in Java Variables are necessary for...

6 minutes read.

History and Evolution of Java

Java is invented by James Gosling, Patrick Naughton, Chris Warth, Ed Frank, and Mike Sheridan at Sun Microsystems, Inc. in 1991. Java is related to C++, which is inherited from...

3 minutes read.

House Numbers in Java

In this section, we will discuss about house number in Java. It is a sum of cubes, each of which has a dimension of h + 1. There is a...

3 minutes read.

Java Enhanced For Loop (For-each Loop)

JAVA ENHANCED FOR LOOP The enhanced for loop is also called the for-each loop and has some advantages over the regular for loop. A for-each loop is designed to cycle through...

4 minutes read.

How to Convert String to long in Java

How to Convert String to long in java It is used when you want to perform the mathematical operation on the String which contains long number then the conversion from String...

4 minutes read.

HashMap Vs HashTable

HashMap HashMap is the basic implementation of the map interface in Java. HashMap stores the data in key and value pairs. Keys are used to access the value of the element. It...

5 minutes read.

Java Enumeration

In a computer language, enumerations express a set of named constants. For instance, the four suits in a deck of playing cards could be represented by the enumerators Club, Diamond,...

4 minutes read.

Java Map Example

In Java, the Map is an interface that is used mainly to denote key and value pairs. The central concept and theme of this mapping in the java collection framework...

4 minutes read.

How to get Day Name from Date in Java

We'll write a Java application to extract the day's name from the Date in this section. When dealing with Date and time in Java, the following classes are used. Class for Calendars:...

6 minutes read.

Applet Program in Java

Applet Program in Java An applet is a program that can be embedded in a web page. Applets programs are run by a web browser. It mainly works on the client-side....

3 minutes read.

Balanced Prime Number in Java

This section will cover the definition of a balanced prime number as well as how to find one using a Java program. Balance Prime Number A prime number that is equivalent to...

5 minutes read.

Short Circuit Logical Operators in Java

When there are two or more relational expressions in a decision-making statement, logical operators are utilized to combine them. The logical operators short circuit and not-short circuit fall into two...

5 minutes read.

Java 9 Try With Resources

Java 9 provides the improvement in the try statement. It allows us to declare a try statement with duly declared resources. Whenever the user does not require the functionality with...

3 minutes read.

How to add 6 Months to the Current Date in Java?

In this tutorial, we will learn how to add 6 months to the local or current date in Java language. We will begin our topic with basic concepts and would...

3 minutes read.

Java ArraylistRemove() Time Complexity

In this tutorial, we will learn about how we can remove time complexity in Java ArrayList. But unless we will not learn what is ArrayList, we don’t understand this process....

7 minutes read.

Java Date add Days

In order to operate with the time and the Date in Java, we used the abstract Calendar class. It has several helpful interfaces that enable us to convert dates between...

4 minutes read.

All the important string methods in Java

What is a String? Strings are a bundle of different characters that are normally used in Java programming language. Strings are regarded as objects in the Java programming language. “String” is a...

4 minutes read.

Normal and Trace of a Matrix in Java

Normal of a matrix The square root of the total squares of each element in a matrix is known as the matrix's normal. Think of the following matrix as an example. Example: [[1,2,3]  ...

3 minutes read.

How to compare characters in Java

In this tutorial, we will learn about how to compare characters in Java. To compare characters in Java, we will learn about what is a character in Java Char The character is...

4 minutes read.