June 19

0  comments

What is Collection Framework in JAVA?

Collection framework in JAVA is a hierarchy of classes and interfaces to provide technology to manage a group of objects.

Collection Framework was not part of the original Java release but was added by J2SE 1.2. Prior to the Collection Framework, Java provided ad hoc classes such as Dictionary, Vector, and Stack to store and manipulate groups of objects.

The collection framework can be represented using the hierarchical model below.

Throughout this article, we will discuss the classes and interfaces mentioned above; the methods available to support handling the group of objects and which one should be used at specific use cases.

What is the difference between Collection, Collection Framework & Collections in JAVA?

Before we proceed to discuss individual classes & interfaces of collection framework, let us have a clear understanding of these terminologies to avoid any confusion.

Collection – In any programming language or real life, a Collection is a group of objects (similar or different).

In JAVA, Collection is an interface present in the java.util package. It is used to represent a group of individual objects as a single unit. Refer to the diagram above.

Collection Framework – Collection Framework in JAVA (as we are focusing on JAVA) is a hierarchical representation of classes and interfaces which provide the framework to deal with a group of objects. Group of objects can be a group of Strings or Integers, or a group of Objects of a particular class etc.

Collections – Collections is a utility class present in java.util package. It defines several utility methods like sorting and searching which are used to operate on collection. All the methods inside Collections class are static.

Explain the collection framework hierarchy. 

We will now visualize and discuss the collection framework hierarchy.

The collection framework contains an interface named Iterable (Iterable is part of java.lang) which is at the topmost position of the framework. Collection interface (from Collection interface onwards, the classes & interfaces are part of java.util package) extends Iterable interface. Collection interface contains all the basic methods like adding the data into the collection, removing the data, clearing the data, etc.

The interfaces below extend the Collection interface.

The Collection interface is extended by 3 major interfaces –

  • List
  • Set
  • Queue

There is one very important thing to notice here is, Map interface does not extend Collection interface. Because some methods declared in Collections do not fit a Map interface and vice versa. So, even if Map does not extend collection, it is a part of the collection framework in java and covered in detail by us.

How do we declare a collection?

Below are the ways we can declare a collection in JAVA:

  1. Collection<Integer> c1  = new ArrayList<Integer>();
  2. Collection c2 = new ArrayList();
  3. Collection<Integer> c1  = new ArrayList< >();

Explanation

Note that Collection is an interface, so we can directly create an object of Collection. Instead, we use any class which implements Collection or child interface of Collection. ArrayList extends AbstractList class which implements List interface which again extends collection. So, while the reference variable c1 is of Collection type, the actual object is of type ArrayList.

Also, using generics/type safety (more about it later) is an optional part while creating a collection. Generics is used to force the user to declare what type of objects they are going to add inside the collection. In example a, user is forced to add only Integers inside c1. Example b allows user to create a collection without generics but might throw ClassCastException while iterating if all the elements inside the Collection are not of the same type. Example c is an enhanced use of generics where declaring the type of object is not necessary in the actual object, but it is still necessary while declaring the reference variable.

What are the methods in Collection interface that are useful for any collection in JAVA?

The methods which Collection interface have inside it, are inherited by all interfaces extend it or classes implement it. So, it is good idea to have generic methods inside the common interface so that they can be reused. Remember that List, Sort & Queue (not Map) can inherit the generic methods from Collection interface reducing duplication of code.

Some of the common methods inside Collection interface are:

  • add(E e) - Objects are added to a collection by calling add( ). It takes an object as an argument.
  • addAll(Collection c) – we can add the content of one collection to another using addAll() method. It takes a collection as an argument.
  • remove(E e) - Objects are removed from a collection by calling add( ). It takes an object as an argument.
  • size() – Return the number of elements in a collection.
  • contains( E e) – Returns true if a collection contains a specific object, which is taken as an argument.
  • iterator() – Returns an iterator over the elements of a collection.

How to iterate over a collection?

Since collection is a group of objects, we need to iterate over the objects very frequently.

In JAVA, we can use 2 common ways to iterate over a collection (group of objects)

Iterate using for each loop

Example –

import java.util.ArrayList;

import java.util.Collection;

public class ForEachDemo {

public static void main(String[] args) {

Collection<String> collection = new ArrayList<String>();

collection.add("zero");

collection.add("one");

collection.add("two");

// for-each loop

for (String s : collection) {

System.out.println("value= " + s);

}

}

}

Output

value= zero
value= one
value= two

Explanation

First, we are creating a collection of type String and adding 3 String values in it. Afterwards, using for-each loop, we are printing the values in the console.

Iterate using Iterator

Iterator is an interface under the java.util package. When we call the iterator() method on a collection, it returns the Iterator. It might sound a little confusing and tricky in the beginning; but the example below will clear those.

import java.util.ArrayList;

import java.util.Collection;

import java.util.Iterator;

public class IteratorDemo {

public static void main(String[] args) {

Collection<String> C1 = new ArrayList<String>(); // Create collection

C1.add("zero");

C1.add("one");

C1.add("two");

Iterator<string> itr = C1.iterator(); // Call iterator() method on C1

 //which returns an Iterator interface.

// while loop

while (itr.hasNext()) {

System.out.println("value= " + itr.next());

}

}

}

Output

value= zero

value= one

value= two

Explanation

First, we are creating a collection of type String. Then we are calling the iterator() method (which is a method in Collection interface) on C1. It returns an Iterator interface (which is being held in itr variable). Now, the Iterator interface has a hasNext() method which checks if the collection has any more elements or not. It also has a next() method which returns the next element in the collection. Using those 2 methods, we are printing the values of collection (C1) in the console.

What is the difference between array and collection?

While both arrays and collections are groups of objects; they have differences. The differences are:

Arrays are fixed in length based on what is declared at the time of creation of the array. But collection size can be changed dynamically based on need.

Arrays are always homogeneous in nature, which means it can store only similar types of data. But collections can store heterogenous data if generics is not in place. Though at runtime, if different types of data is stored, a collection throws ClassCastException while iterating it.

Arrays do not provide any built-in utility methods like sorting, searching etc. but Collection includes readymade methods to use.

What is Generics and what is its benefit?

Generics allow us to provide the type of Object that a collection can contain.

Generics was added in Java 5 to provide compile-time type checking and remove the risk of ClassCastException that was common while working with collection classes. The whole collection framework was re-written to use generics for type-safety.

Let’s see the benefit of Generics using below programs.

1. Collection without Generics

public class Main {

            public static void main(String[] args) {

                        List list = new ArrayList();

                        list.add("abc");

                        list.add(5); // OK

                        for (Object obj : list) {

                                    // type casting leading to ClassCastException at runtime

                                    String str = (String) obj;

                                    System.out.println(obj);

                        }

            }

}

Output

abc

Exception in thread "main" java.lang.ClassCastException: class java.lang.Integer cannot be cast to class java.lang.String

Explanation

Above code compiles fine but throws ClassCastException at runtime because we are trying to cast Object in the list to String whereas one of the elements is of type Integer.

2. Collection with generics

We can avoid this issue of ClassCastException by forcing the user to store only similar types of data in the collection.

public class Main {

            public static void main(String[] args) {

                        List <String > list = new ArrayList<>();

                        list.add("abc");

                        //list.add(5); // compilation error

                        for (String str : list) {

                                    System.out.println(str);

                        }

            }

}

Output

abc

Explanation

At the time of list creation, we have specified that the type of elements in the list will be String. So, if we try to add any other type of object in the list, the program will throw a compile-time error. Also notice that for each loop, we don’t need typecasting of the element in the list, hence removing the possibility of ClassCastException at runtime.


Tags


You may also like

API Basics and Architecture

API Basics and Architecture
Leave a Reply

Your email address will not be published. Required fields are marked

{"email":"Email address invalid","url":"Website address invalid","required":"Required field missing"}