🙄

Collection Interface in Java

2022/05/29に公開

In every programming language, collections are utilised. They are objects that club several elements into one single unit. It was troublesome for developers to frame algorithms that worked for various kinds of collections.

Java showed up with a few Collection classes, such as Hashtable, Vector, Stack, and Array, but they came with their pitfalls. In JDK 1.2, the Collections Framework was introduced by Java programmers, which is a powerful framework to help you accomplish all of your data operations.

In this article, we’ll learn about this framework and some of its components.

What is a Java Collection Framework?

Java Collection Framework offers the capability to Java Collection to represent a group of elements in classes and Interfaces. Java Collection Framework enables the user to perform various data manipulation operations as storing data, insertion, searching, sorting, deletion, and updating data on the group of elements.

Followed by the Java Collections Framework, you must read and comprehend the different descendants or classes and interfaces involved in the Java Collections and Hierarchy of Java collections.

A Java collection framework includes:

  • Interfaces
  • Classes
  • Algorithm

Let’s look at them:

1.Interfaces: These interfaces provide the abstract data type to display the collection. Being the root interface of the framework, the java.util.Collection is at the top of the framework hierarchy and consists of essential methods, including add(), size(), iterator(), remove(), and clear().
Being the root of the whole collection framework, iterable interface lets the iterator to iterate via all the collections. All interfaces and classes make use of this interface. The collection interface expands the iterable interface and is executed by the classes in the collection framework. The list interface inhibits a list type data structure where the ordered collections of objects can be stored.

A few of the more significant interfaces include:

  • Set interface: java.util.Set
    Enforces uniqueness constraints - can’t contain duplicate elements. It doesn’t trouble itself with the order of iteration within itself, since it models the mathematical set abstraction. Sets offer no additional functionality other than the inherited from Collections.
  • Map interface: java.util.Map
    Even though java.util.Map implementations aren’t regarded “true collections”, as they offer collection-view operations which practically facilitate them collection-level manipulation. It is a collection of pair and isn’t a collection of individual values. These are associations between values (Maps) and unique keys that can be looked up from those keys. It’s crucial to note that the keys are unique, and each key is associated with a value, but a value can be associated with over one key.

Deque interface: java.util.Deque
Similar to queues, double-ended queues (reduced to deques) additionally offer the possibility of performing operations on elements from both sides of the queue.

Below are the methods of Deque interface

It is to be noted that the Map interface is included in the Collections Framework but is the only one that doesn’t inherit from the Collection interface. All framework interfaces are in the java.util package.

  • Classes: Classes in Java are the implementation of the collection interface. Basically, it indicates to the data structures that are utilized repeatedly. A few of the important collection classes comprise:

    • LinkedList
    • ArrayList
    • PriorityQueue
    • HashMap and HashSet
    • TreeMap and TreeSet
  • Algorithm: Algorithm indicates the techniques which are utilised to accomplish operations including searching and sorting, on objects that incorporate collection interfaces. Being polymorphic in nature, in Algorithm the same method can be used to take many forms or you can say perform different implementations of the Java collection interface.

Therefore, why do you think we require Java collections? The Java collection framework offers the programmers to access prepackaged data structures and algorithms to manipulate data.

Interface Collection

As stated above, within the Java API, all the collection interfaces extend a common interface- <code>java.util.Collection</code>. This primary interface provides all the common collections functionality. Let us check the hierarchy of Collection framework.

Every sub-interface has various implementations, and a few of these sub-interfaces offer additional operations:

The important point to figure out is that each interface describes behavior and functional characteristics where we can use numerous data structures while implementations determine performance characteristics, utilize a specific data structure and are instantiable.

The collection interface is at the top of collection heirarchy and must be incorporated by any class that defines a collection. Its general declaration is,

interface Collection <E>

The most commonly used methods in the <code>Collection</code> interface are:


Types of Interface in Java

a Set Interface in Java
Set accumulation that doesn’t allow copies and furthermore doesn’t allow getting to components by index. Instead, it offers methods that review if component or components exist.
- EnumSet – The EnumSet is one of the specialized implementations of the Set interface for use with the enumeration type. Some of the essential features of EnumSet are:
- EnumSet implements Set Interface and extends AbstractSet class in Java.
- EnumSet class is not synchronized and a member of the Java Collections Framework.
- It’s a high-performance set implementation, much faster than HashSet.
- All elements in an EnumSet must come from a single enumeration type that is mentioned when the set is explicitly or implicitly built.
- Null Objects is not allowed and throws NullPointerException if we do so.
- It utilizes a fail-safe iterator, thus it won’t throw ConcurrentModificationException if the collection is changed while iterating.

Set can be instantiated as:

Set<data-type> s1 = new HashSet<data-type>();  
Set<data-type> s2 = new LinkedHashSet<data-type>();  
Set<data-type> s3 = new TreeSet<data-type>();  
  • HashSet – Java HashSet class is employed to set up a collection that makes use of a hash table for storage. It inherits the AbstractSet class and implements Set interface.
    Let’s look at a few of the essential points about Java HashSet class are:
    • HashSet stores the elements by making use of a mechanism called hashing.
    • HashSet consists of only unique elements.
    • HashSet class is non synchronized.
    • HashSet allows null value.
    • The insertion order is not maintained in HashSet. Here, elements are inserted based on their hashcode.
    • HashSet is an outstanding approach for search operations.
    • The initial default capacity of HashSet is 16, and the load factor is 0.75.

Consider the following example

import java.util.*;  
public class TestJavaCollection7{  
public static void main(String args[]){  
//Creating HashSet and adding elements  
HashSet<String> set=new HashSet<String>();  
set.add("Ravi");  
set.add("Vijay");  
set.add("Ravi");  
set.add("Ajay");  
//Traversing elements  
Iterator<String> itr=set.iterator();  
while(itr.hasNext()){  
System.out.println(itr.next());  
}  
}  
}  

Output:

Vijay
Ravi
Ajay

- LinkedHashSet – Java LinkedHashSet class is a Hashtable and Linked list implementation of the Set interface. It inherits the HashSet class and implements the Set interface.

Let’s look at the essential points about the Java LinkedHashSet class:

  • Java LinkedHashSet class comprises unique elements only like HashSet.
  • Java LinkedHashSet class is non-synchronized.
  • Java LinkedHashSet class offers all optional set operations and allows null elements.
  • Java LinkedHashSet class retains insertion order.

- TreeSet – One of the most prominent implementations of the SortedSet interface in Java, TreeSet makes use of a Tree for storage. A set maintains the ordering of the elements with the help of their natural ordering, whether or they provide not an explicit comparator. This has to be consistent with equals if it is to implement correctly the Set interface. A Comparator given at set creation time can also order it, which depends on the constructor that is utilised. By inheriting AbstractSet class, the TreeSet implements a NavigableSet interface. The navigable set extends the sorted set interface since a set doesn’t retain the insertion order, the navigable set interface offers the implementation to navigate through the Set. The class which implements the navigable set is a TreeSet which is an implementation of a self-balancing tree. Thus, this interface offers us with a way to navigate through this tree.

- SortedSet – A sorted set is a set with ordering on its elements. SortedSet interface represents a sorted set in Java Collection Framework. They can sort the elements in a SortedSet in a natural order by using a Comparator or with Comparable interface. A SortedSet should know the way to sort its elements since they are added by checking two interfaces:
- If its elements implement the Comparable interface, it will utilise the compareTo() method to sort items. We can call this as sorting in natural order.
We can passin a Comparator to perform custom sorting.
- If a Comparator is specified, the Comparator is utilised for sorting and ignore the Comparableinterface. In the Collections Framework, the TreeSet class is an implementation for the SortedSet interface.

b. Java List Interface
This interface depicts a collection of elements whose elements are arranged sequentially. List retains an order of elements, implying the order is maintained in which we add elements, and the same sequence we will get while retrieving elements. At any location, we can insert elements into the list. The list lets you store duplicate elements in Java.

- ArrayList – An ArrayList class is a resizable array, which is present in the java.util package. ArrayLists can change their size dynamically while built-in arrays have a fixed size. Elements can be added and erased from an ArrayList whenever there is a requirement, assisting the user with memory management. Let us take a look at a few of the important features:
- ArrayList implements the List interface and inherits AbstractList class.
- ArrayList is initialized by the size. Nevertheless, the size is raised automatically if the collection expands or shrinks if the objects are taken out from the collection.
- Java ArrayList lets us to access the list randomly.
- We cannot use arrayList for primitive types, such as int, char, etc. We require a wrapper class for such cases.
- We can see ArrayList in Java as a vector in C++.
- ArrayList is not Synchronized. It’s equal to synchronized class in Java is Vector.

  • LinkedList – Being data structure, linked list is made of a chain of node objects. Every node comprises a pointer and a value to the subsequent node in the chain. I prefer linked lists over arrays owing to their dynamic size and flexibility of insertion and deletion properties.
    Here is the declaration for Java LinkedList class:
public class LinkedList<E>
extends AbstractSequentialList<E>
implements List<E>, Deque<E>, Cloneable, Serializable 

LinkedList in Java implements the abstract list interface and inherits different constructors and methods from it. LinkedList also implements the Deque interface. A doubly linked list is utilised to store the elements. Thus, this sequential data structure can be utilised as a stack, list, or queue.

- Vector – Vectors in Java are one of the most popularly utilised data structures in the programming world. It is a well known fact that Arrays are data structures that hold the data in a linear fashion. Vectors also store the data in a linear fashion, but unlike Arrays, they do not have a fixed size. Rather, their size can be expanded in demand. Being a child class of AbstractList class, Vector class implements on List interface. To utilise Vectors, we have to first import Vector class from java.util package:

import java.util.Vector

c. Map Interface in Java

Java Map Interface is an accumulation that allows copies and is like rundown except for that record components by (key can be any protest) Map can be expected as an affiliated exhibit.

- HashMap – A part of Java’s collection, in HashMap, an index of a type can access store items in value/key pairs. The keys are the unique identifiers utilised for associating every value on a map. HashMap in Java can access the data much quicker and simpler. Every key should be mapped to one value exactly, and it is utilised to recover the corresponding value from a map. If the duplicate key is inserted, the element of the corresponding key is replaced. HashMap in the Java class is found in the java.util package and it offers the implementation of the map interface of Java.
- LinkedHashMap – A Hash table, LinkedHashMap is linked list implementation of the Map interface, with predictable iteration order. This implementation varies from HashMap because it maintains a doubly-linked list running through all of its entries. This linked list describes the iteration ordering, normally this is the order in which keys were inserted into the map (insertion-order). This class is different from both of them:
- HashMap order is not maintained.
- TreeMap the entries should be sorted in ascending order of keys.
- LinkedHashMap maintains the insertion order.
- TreeMap – Based NavigableMap implementation, TreeMap is Red-Black tree. It is sorted as per the natural ordering of its keys. TreeMap class implements Map interface identical to HashMap class. The major distinction between them is that TreeMap is sorted in the ascending order of its keys while HashMap is an unordered collection. TreeMap is an unsynchronized collection class which implies it is not good enough for thread-safe operations until and unless synchronized explicitly. A few of the essential features of the treemap are:
- TreeMap class is a member of the Java Collections Framework.
- The class implements Map interfaces such as Sorted map, NavigableMap, and extends AbstractMap class.
- TreeMap in Java does not permit null keys (like Map), hence a NullPointerException is thrown. Nevertheless, several null values can be associated with various keys.
- Entry pairs returned by the methods in this class and its views display glimpses of mappings at the time they were produced. Entry.setValue method is not supported.
- Entry pairs returned by the methods in this class and its views represent snapshots of mappings at the time they were produced. They do not support the Entry.setValue method.

- Hashtable – A concrete implementation of abstract Dictionary class, Hashtable class in Java is a data structure comparable to Java HashMap that can save a collection of elements (objects) as key-value pairs (entries). Key objects must implement equals() and hashCode() methods to store and retrieve values from the Hashtable.In other words, Hashtable can store only key objects that override equals() and hashCode() methods described by the Object class. The major difference between HashMap and Hashtable and is the way they function with thread access.
- A synchronized class, Hashtable class implies it is thread-safe. Several threads cannot access the same instance of the Hashtable class concurrently (at the same time).
- HashMap class is not synchronized, which implies it is not thread-safe. Simultaneously, several threads can access the same instance of HashMap class. Thus, it is safe to utilise only when one thread uses an object.

- EnumMap – One of the specialized implementation of Map interface for use with enum type keys, EnumMap was introduced in Java 1.5 with enumeration type. All the keys in an enum map must come from a single enum type that is explicitly or implicitly mentioned when the map is set up. Enum maps are displayed internally as arrays. This representation is very compact and effective. Often, developers utilise HashMap to store enum type, as they are unaware of this little gem.
Features:
- Java EnumMap inherits AbstractMap class.
- All keys of every EnumMap instance has to be keys of a single enum type.
- Java EnumMap does not allow null key, but allows several null values.
- Iterators returned by the collection views are poorly consistent: they will never throw ConcurrentModificationException and they can or cannot display the effects of any changes to the map that appear while the iteration is in progress.
- Enum maps are maintained in the natural order of their keys as the order in which the enum constants are declared).

- Properties – HashTable’s sublcass, the Properties class describes a constant set of properties. The Properties can be loaded from a stream or can be saved to a stream. Belonging to java.util package, properties describe the following instance variable. This variable holds a default property list related with a Properties object. Aspects of a Properties class:
- It is a subclass of Hashtable.
- Properties is utilised to manage a list of values where the value is a string and the key is a string i.e; it can store and recover string type data from the properties file.
- This class can define other properties list as it’s the default. If a certain key property doesn’t exist in the original Properties list, the default properties will be searched.
- Properties object does not need external synchronization and several threads can share a single Properties object.
- Also, it can retrieve the properties of the system.

Examples of Collection Interface in Java

Mentioned below is an example of Collection Interface in Java:

Example #1

In this instance, the methods of collection interface in java are shown. We will see how to use add, addAll and size method.

package com.edubca.nonprimitivedemo;
// import collections
import java.util.ArrayList;
import java.util.List;
public class DataTypeDemo {
public static void main(String[] args) {
List arraylist1 = new ArrayList();
// Adding elements to arraylist
arraylist1.add("Yash");
arraylist1.add("Montu");
arraylist1.add("Ketan");
System.out.println(" ArrayList1 Elements are :");
System.out.println("\t" + arraylist1);
//printing size of arraylist1
System.out.println("Size of ArrayList1 is " +arraylist1.size() );
List arraylist2 = new ArrayList();
// Adding elements to arraylist
arraylist2.add("Chetan");
arraylist2.add("Chirag");
arraylist2.add("Ali");
System.out.println();
System.out.println(" ArrayList2 Elements are :");
System.out.println("\t" + arraylist2);
//printing size of arraylist2
System.out.println("Size of ArrayList1 is " +arraylist2.size() );
System.out.println();
// Adding elements of both lists to list1
arraylist1.addAll(arraylist2);
// Now Printing modified list
System.out.println(" ArrayList1 Elements after merging with ArrayList2 are : ");
System.out.println("\t" + arraylist1);
//printing size of arraylist1
System.out.println("Size of ArrayList1 is " +arraylist1.size() );
}
}

Output

ArrayList1 Elements are
[Yash, Montu, Ketan]
Size of ArrayList1 is
ArrayList2 Elements are
[Chetan, Chirag,
Alil
Size of ArrayList1 is 3
ArrayList1 Elements after merging with ArrayList2 are
[Yash, Montu, Ketan,
Chetan, Chirag, Ali]
Size of ArrayList1 is 6

2. Removing Elements

The removeAll(Collection c) and remove(E e) methods can be utilised to erase a certain element or a collection of elements from a collection.

// Java program to demonstrate removing
// elements from a Collection
 
import java.util.*;
 
public class RemoveElementsExample {
    public static void main(String[] argv) throws Exception
    {
 
        // Creating object of HashSet<Integer>
        Collection<Integer> set1 = new HashSet<Integer>();
 
        // Populating arrset1
        set1.add(1);
        set1.add(2);
        set1.add(3);
        set1.add(4);
        set1.add(5);
 
        // print set1
        System.out.println("Initial set1 : " + set1);
         
          // remove a particular element
          set1.remove(4);
       
          // print modified set1
        System.out.println("set1 after removing 4 : " + set1);
       
        // Creating another object of HashSet<Integer>
        Collection<Integer> set2 = new HashSet<Integer>();
        set2.add(1);
        set2.add(2);
        set2.add(3);
 
        // print set2
        System.out.println("Collection Elements to be removed : " + set2);
 
        // Removing elements from set1
        // specified in set2
        // using removeAll() method
        set1.removeAll(set2);
 
        // print arrset1
        System.out.println("set 1 after removeAll() operation : " + set1);
    }
}

Output

Initial set1 : [1, 2, 3, 4, 5]
set1 after removing 4 : [1, 2, 3, 5]
Collection Elements to be removed : [1, 2, 3]
set 1 after removeAll() operation : [5]

Need for Interface in Java

So we require an Interface in Java because:

  • Total Abstraction
  • Multiple Inheritance
  • Loose-Coupling

Total Abstraction

One of the critical concept of Object-Oriented programming techniques is Abstraction. An interface only saves the method signature and not the method definition. Method Signatures make an Interface obtain complete Abstraction by hiding the method implementation from the user.

Multiple Inheritance

The process of multiple inheritances is unattainable without Interface, since the traditional way of inheriting multiple parent classes results in serious ambiguity. We know this type of ambiguity as the Diamond problem. Interface resolves this issue.

Loose Coupling

The term Coupling defines the dependency of one class for the other. Hence, while utilising an interface, we describe the method and the signature separately. This way, all the classes and methods are fully independent and archives Loose Coupling.

Disadvantages of Interface in Java

In real-world projects, an interface is utilised either extensively or not at all.
Using Interface can reduce the execution speed.

So these were a couple of pitfalls to using an interface in Java.
With this, we have now come to the end of the “Interface in Java’ article. We hope you have enjoyed reading about the important concepts of Interface in Java. The interface is only one of the crucial concepts of Object-Oriented Programming in Java. We highly recommended to read all the Object-Oriented Programming Concepts in Java for a better understanding and the interdependency of OOPs Concepts in Java.

Discussion