Both Collection and Collections reside in java.util.package. The main difference between them is, Collection is an interface for specifying methods that needs to be implemented by all the collection class whereas Collections is a class that offers utility methods to work with collections.
Basis | Collection | Collections |
---|---|---|
Definition | In Collection hierarchy, it is the root interface that represents a group of objects, termed as elements | It is a class that provides utility methods which operates on collection objects. |
Represents | Class | Interface |
Purpose | It specifies group of objects as single entity and supports various method that can be applied on collection objects | It specifies predefined utility methods which are used for operations i.e searching, sorting for collection objects |
Methods | It consists static, abstract and default methods | It consists only static methods |
The collection is an interface that represents a group of individual objects as a single entity. It is the root interface of the collection framework that specifies several methods which are applied to all collections.
The collection interface is inherited by List, Set and Queue interfaces and its implementing classes are ranging from ArrayList to TreeSet.
Syntax :
public interface Collection<T> extends Iterable<T>
contains(), add(), isEmpty(), remove() and clear() are some of the important methods
Collections is a utility class that consists of static methods which operate on collections. It provides handy methods that can be used directly on collection objects such as searching and sorting purposes.
Syntax:
public class Collections extends Object
Program:
public class CollectionExample { public static void main(String[] args) { List<String> names = new ArrayList<>(); names.add("Sandeep"); // add() method is a method of collection interface names.add("Vinay"); names.add("Kui"); names.add("Sachin"); System.out.println("Before sorting :: "+ names); Collections.sort(names); // sort() would sort a list in natural order System.out.println("After sorting :: "+ names); } }
Output:
Before sorting :: [Sandeep, Vinay, Kui, Sachin] After sorting :: [Kui, Sachin, Sandeep, Vinay]
This post was last modified on July 4, 2023