Monday, September 26, 2022
HomeBig DataCollection and Collections: What is the Difference?

Collection and Collections: What is the Difference?

[ad_1]

The difference between Collection and Collections is a crucial interview question for freshers and over time has been used to test the knowledge of the Java Collections Framework. Both are part of the java collection framework, but both serve different purposes. They are commonly used in Java programming and are available in java.util package. Collections is a utility class, whereas Collection is a top-level interface of the java collection framework. Overall, Collection allows storing several objects as one Collection object. On the other hand, Collections allow performing operations on that object. In this article, we will learn about the differences between Collection and Collections in java.

Without using collection concepts, you cannot develop any production level software application in Java. Therefore, every Java learner has to have a good grasp of the collections framework. As per the Sun Microsystem document, among all the java concepts, the Java collections framework is the most crucial concept for developing the project.

What is Collections Framework in Java?

A Java collections framework is a sophisticated hierarchy of different predefined interfaces and implementation classes that can be utilised to deal with a group of objects as a single entity. Both Collection and Collections are part of the Java Collections Framework and are present in java.util package. Also, both Collection and Collections are added to JDK in java version 1.2

The Java collections framework supports two kinds of containers:

  1. One is for storing a collection of elements (objects), which is regarded as a collection.
  2. Another for storing key/value pairs is termed a map.

A collections framework is a unified architecture for representing and manipulating collections. All collections frameworks include:

  1. Interfaces Interfaces are abstract data types that exhibit collections. Interfaces let collections to be manipulated independently of the details of their representation. In object-oriented languages, interfaces form a hierarchy.
  2. Implementations, i.e., Classes These are the concrete implementations of the collection interfaces. They are reusable data structures.
  3. Algorithms These are the methods that execute useful computations, like searching and sorting, on objects that implement collection interfaces. The algorithms are said to be polymorphic, which means the same method can be utilised in many implementations of the appropriate collection interface.

The java collections framework offers an API to function with data structures like lists, maps, trees, and sets. The list of interfaces is defined in java.util package is depicted in the table below:

Collection List Queue
Comparator ListIterator RandomAccess
Deque Map Set
Enumeration Map.Entry SortedMap
EventListener NavigableMap SortedSet
Formattable NavigableSet
Iterator Observer

Java Collection Framework hierarchy:

Advantages of collections framework:

  1. We dont have to learn different ad hoc collection APIs.
  2. It offers a standard interface for collections that facilitates software reuse and also offers algorithms to manipulate them.
  3. Cuts down the effort needed to design and incorporate APIs by excluding the need to produce ad hoc collections APIs.
  4. It offers suitable data structures and algorithms that cut down programming effort owing to which we need not write them ourselves.
  5. It offers high-performance implementations of useful data structures and algorithms that enhance performance.
  6. Aids in establishing a common language for passing collections back and forth that provides interoperability between unrelated APIs.
  7. The collection is resizable and can grow.

Disadvantages of collections framework:

  1. It has to be cast to the correct type.
  2. It cant be done compile-time type checking.

The collection framework has various predefined algorithms and these can be applied to the Collection and Map interface. We define these algorithms as static methods and are present inside the Collection interface. These algorithms are polymorphic, meaning we can implement them as many times as needed. A few of these methods can exhibit a ClassCastException, which arises when an attempt is made to compare incompatible types, or an UnsupportedOperationException, which arises when an attempt is made to change an unmodifiable collection.

The following table explains 10 of the collection framework algorithms out of the many:

Sr.No. Method Description
1 static int binarySearch(List list, Object value, Comparator c) This method looks for a value in the list ordered as per c. Returns the position of value in the list, or -1 if the value is not found.
2 static int binarySearch(List list, Object value) This method looks for a value in the list. The list has to be sorted. It returns the position of value in the list, or -1 if they do not find the value.
3 static void copy(List list1, List list2) This method involves copying the elements of list2 to list1.
4 static Enumeration enumeration(Collection c) An enumeration over c is returned by this method.
5 static void fill(List list, Object obj) Every element of the list is assigned an object by this method.
6 static int indexOfSubList(List list, List subList) This method looks for a list for the first occurrence of subList. Returns the index of the first match, or .1 if no match could be found.
7 static int lastIndexOfSubList(List list, List subList) This method looks for a list for the last occurrence of subList. Returns the index of the last match, or .1 if no match could be found.
8 static ArrayList list(Enumeration enum) This method returns an ArrayList that includes the elements of an enum.
9 static Object max(Collection c, Comparator comp) This method returns the maximum element in c as determined by comp.
10 static Object max(Collection c) This method returns the maximum element in c as determined by natural ordering. There is no need for the collection to be sorted.

Code to elucidate the use of algorithms:

package com.DataFlair.CollectionFramework;
import java.util.*;
public class Algorithms
{
public static void main(String args[]) {
LinkedList L1 = new LinkedList();
L1.add(new Integer(15));
L1.add(new Integer(2));
L1.add(new Integer(-2));
L1.add(new Integer(1000));
Comparator r = Collections.reverseOrder();
Collections.sort(L1, r);
Iterator li = L1.iterator();
System.out.print(“List sorted in reverse: “);
while(li.hasNext()) {
System.out.print(li.next() + ” “);
}
System.out.println();
Collections.shuffle(L1);
li = L1.iterator();
System.out.print(“List shuffled: “);
while(li.hasNext()) {
System.out.print(li.next() + ” “);
}
System.out.println();
System.out.println(“Minimum: ” + Collections.min(L1));
System.out.println(“Maximum: ” + Collections.max(L1));
}
}

Output:

List sorted in reverse: 1000 15 2 -2
List shuffled: 15 -2 2 1000
Minimum: -2
Maximum: 1000

As we can see from the example, using algorithms can make programs crisp and simple.

Collection Interface:

Collection interface is the basic interface of the collections framework where the root interface of all collections is in the API (Application programming interface). It is situated at the top of the collection hierarchy in java. The collection interface provides the fundamental operations for adding and deleting elements in the collection and extends the Iterable interface. The iterable interface contains just one method called iterator(). The work of the iterator method is to return the iterator object. With the help of this iterator object, we can iterate over the elements of the collection. The collection hierarchy comprises six interfaces, the core collection interfaces. Three such interfaces, namely Set, List, and SortedSet are the descendants of the Collection interface. They further add constraints on the contracts imposed by the methods at this interface, along with adding new methods. The other two core collection interfaces, Map and SortedMap, are not descendants of Collection, as they represent mappings instead of true collections.

The other important interfaces in Collection and all the methods that modify the collection are labelled optional. Some implementations may not function with one or more of these operations, and if they are attempted, it throws a runtime exception, UnsupportedOperationException. Implementations have to mention in their documentation which optional operations they support. To aid in this specification, there are several terms are introduced.

  • Collections that do not support any modification operations, including add, remove, and clear, are termed as unmodifiable. Collections that can be modified are referred to as modifiable.
  • Collections that additionally assure that no modification in the Collection will ever be observable via query operations like size, iterator, contains are termed as immutable. Mutable ones are collections that are not immutable.
  • Lists that assure that their size will stay constant despite the elements getting changed are termed as fixed-size. Lists that are not fixed-size are called as variable-size.

Syntax:

public interface Collection extends Iterable

Mentioned below are a few of the commonly used methods in this interface.

Methods Description
boolean add( E obj ) This method is utilised to add objects to a collection. If obj was added to the collection, it returns true. If obj is already a member of the collection, or if the collection does not allow duplicates, it returns false.
boolean addAll( Collection C ) Add all elements of collection C to the invoking collection. If the element were added, returns true if. Else, returns false.
boolean remove( Object obj ) To delete an object from collection. If the element was removed, returns true. Else, returns false.
boolean removeAll( Collection C ) Removes all element of collection C from the invoking collection. If the collections elements were removed, it returns true. Else, returns false.
boolean contains( Object obj ) To figure out whether or not an object is present in collection. If obj is an element of the invoking collection, returns true. Else, returns false.
boolean isEmpty() If collection is empty, returns true. Otherwise, returns false.
int size() Returns number of elements present in collection.
void clear() Deletes the total number of elements from the collection.
Object[] toArray() Returns an array which comprises the invoking collection elements.
boolean retainAll(Collection c) Removes all the elements of invoking collection other than the specified collection.
Iterator iterator( ) Returns an iterator for the invoking collection.
boolean equals(Object obj) If the invoking collection and obj are equal, returns true. Else, returns false.
Object[] toArray(Object array[]) Returns an array comprising just those collection elements whose type matches of the specified array.

Example:

Lets look at this example where we will show methods of collection interface in java. We will see how to use add, addAll and size method.

Code:

// 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 3

ArrayList2 Elements are :
[Chetan, Chirag, Ali]
Size of ArrayList1 is 3

ArrayList1 Elements after merging with ArrayList2 are :
[Yash, Montu, Ketan, Chetan, Chirag, Ali]
Size of ArrayList1is 6

Collections

A utility class in java.util package, Collections comprises only static methods which are utilised to operate on objects of type Collection. It defines several utility methods, such as sorting and searching, which are utilised to operate on the collection and contain all static methods. These methods offer much-required convenience to programmers, letting them efficiently function with the Collection Framework. For instance, It has a method sort(), intended to sort the collection elements as per the default sorting order, and it has a method min(), and max() to look for the minimum and maximum values respectively in the collection elements.

Collections class fields

Basically, the collection class basically comprises 3 fields as mentioned below which can return immutable entities.

  • EMPTY_SET to get an immutable empty Map.
  • EMPTY_LIST to get an immutable empty List.
  • EMPTY_MAP to get an immutable empty Set.

Syntax:

public class Collections extend Object

Mentioned below is the list of a few of the significant methods of the Collections class.

Collections.max() It returns the maximum element in the given collection.
Collections.min() This method returns the minimum element in the mentioned collection.
Collections.sort() It sorts the given collection.
Collections.shuffle() It randomly shuffles the elements in the given collection.
Collections.synchronizedCollection() It returns the synchronized collection supported by the specified collection.
Collections.binarySearch() This method looks for the given collection for the specified object with the help of a binary search algorithm.
Collections.disjoint() If two specified collections have no elements in common, it returns true.
Collections.copy() It copies all elements from one to another collection.
Collections.reverse() The order of elements in the given collection is reversed in this method.

Example:

import java.util.*;
public class Main {

public static void main(String args[])
{
//Creating ArrayList Object
ArrayList students = new ArrayList<>();

//Adding elements to the ArrayList
students.add(“Jai”);
students.add(“Manish”);
students.add(“Vikram”);
students.add(“Mahesh”);
students.add(“Naren”);

//Print ArrayList
System.out.println(“ArrayList elements: ” + students);

// Print minimum value
System.out.println(“Minimum value: ” + Collections.min(students));

// print maximum value
System.out.println(“Maximum value: ” + Collections.max(students));
}
}

Output

ArrayList elements: [Jai, Manish, Vikram, Mahesh, Naren]
Minimum value: Jai
Maximum value: Vikram

Category Collection Collections
Type It is the high-level interface of all other child interfaces and classes of the Java Collection framework. The Collection interface includes the core methods for all collections. Collections class in java shows an utility class in java.util package. It consists of only static methods that operate on or return collections. It comprises polymorphic algorithms that operate on collections, wrappers, which in turn return a new collection backed by a specified collection.
Static methods Since Java 8, the collection interface can contain static methods, abstract and default methods. Before java8, the interface was not allowed to contain static methods. Collections class includes only static methods and has polymorphic algorithms that operate on collections, wrappers, which return a new collection backed by a given collection. All the methods of this class throw a NullPointerException if the collections or class objects given to them are null.
extends

Collection interface extends iterable interface.

public interface Collections
extends Iterable

Collections class extends Object class.

public class Collections
extends Object

Consist of The collection includes sub-interfaces like List, Set, and Queue. Collections include static utility methods like sort, reverse, etc.
Usage Collection aids in storing a set of objects into a single Collection object. Collections assists in performing an operation on the object of Collection.

Conclusion

The Java collections framework provides the developer access to prepackaged data structures along with access to algorithms for manipulating them. There is a distinction between Collection and Collections though most people utilise these two terms interchangeably. The major difference between Collection and Collections is that Collection is the root interface of the Java Collections Framework, whereas Collections is a utility class which is a member of the Java Collections Framework. In a nutshell, Collection is an interface whereas Collections is a class.

The post Collection and Collections: What is the Difference? appeared first on Datafloq.

[ad_2]

Source link

RELATED ARTICLES

LEAVE A REPLY

Please enter your comment!
Please enter your name here

Most Popular

Recent Comments