Collection vs Collections in Java

Collection:

In Java, "Collection" (without an 's') is an interface that's a part of the Java Collections Framework. Now, what's an interface? Think of it as a set of rules that classes need to follow. So, when we say "Collection" in Java, we're talking about a set of rules that classes can follow to be considered a collection.


Example:

import java.util.ArrayList;

import java.util.Collection;



   public class MyCollection implements Collection<string> {

       // Here we can Implement the methods defined by the Collection interface

   }

Here, `MyCollection` is a class that follows the rules set by the `Collection` interface.


Collections:

In addition to the `Collection` interface Java provides a separate class called `Collections` (with an 's' at end) that contains utility methods for working with collections. The `Collections` class is of the Java API and offers a wide range of static methods that can be used to perform common operations on collections. 

It provides methods like:

sort(): To sort the elements of a collection in a natural order or using a custom comparator.

binarySearch(), indexOf(): This method allows you to search for specific elements within a collection.

max(), min(): Returns maximum and minimum element in a collection.

reverse(): To reverse the order of elements in a list.

shuffle(): It is use to Randomizes the order of elements in a list.

It provides more methods like copy(), synchronizedMap(), synchronizedList() etc...


Example:

import java.util.ArrayList;

   import java.util.Collections;



   public class MyArrayList {

       public static void main(String[] args) {

           ArrayList<String> myList = new ArrayList<>();

           myList.add("Audi");

           myList.add("BMW");

           myList.add("Tesla");



           // Here we are using Collections class to shuffle the list

           Collections.shuffle(myList);

           System.out.println("Shuffled List: " + myList);

       }

   }

In this example, `Collections.shuffle()` is a method provided by the `Collections` class. It shuffles the elements in the `ArrayList`.


Key Differences:

   - "Collection" is an interface defining a set of rules for classes, while "Collections" is a utility class offering methods to work with objects that implement the "Collection" interface.

   - When we say "Collection," we're talking about the concept of a group of objects. When we say "Collections," we're referring to the toolbox of methods we can use when dealing with these groups.


In Summary:

   - "Collection" is like a blueprint for classes that want to be considered collections.

   - "Collections" is like a toolbox providing helpful methods when working with collections.


No comments:

Post a Comment

If you have any doubts, please discuss here...👇