MainMenu

Home Java Overview Maven Tutorials

Wednesday, 22 April 2020

Difference Between Collection & Collections




Difference between Collection & Collections

Difference between Collection and Collections

1). Collection is a root level Interface in Java Collection Framework or collection hierarchy. The Set, List and Queue are the some of the subInterfaces of Collection interface.

The important methods of Collection interface are add(), remove(), size(), clear() etc.

Collections is a utility class in java.util package which contains only static methods that operate on objects of type collection.

Collections class contains only static methods like sort(), min(), fill(), copy(), reverse() etc.

2). Before Java 8, interface was not allowed to contain static methods. collection is an Interface & interface can contain static methods since java 8 and Interface can also contain abstract methods and default methods.

But collections class contains only static methods.



3). Collection interface extends iterable interface

public interface Collections extends Iterable

and Collections class extends Object class

public class Collections extends Object



Similarities between Collection and Collections in Java



1). Both are part of the Java Collections Framework.

2). Both are present in java.util package

3). Both are added to jdk in java version 1.2





Example of Collections

import java.io.*;
import java.util.ArrayList;
import java.util.*;

public class ConsTest
{
public static void main(String args[]) throws IOException
{
ArrayList alist = new ArrayList();
alist.add(10);
alist.add(20);
alist.add(5);
alist.add(35);
alist.add(45);
System.out.println("maximum value" + " " + Collections.max(alist));
System.out.println("maximum value" + " " + Collections.min(alist));
ArrayList list = new ArrayList();
list.add("Chandan");
list.add("Chauhan");
list.add("Cha");
Collections.sort(list);
System.out.println("Sorted Strings" + " " + list);
Collections.sort(list, Collections.reverseOrder());
System.out.println("Reversed Strings" + " " + list);
ArrayList slist = new ArrayList(3);
slist.add("Chandan");
slist.add("Chauhan");
slist.add("Cha");
ArrayList dlist = new ArrayList(3);
dlist.add("a");
dlist.add("b");
dlist.add("c");
Collections.copy(dlist, slist);
System.out.println(dlist);
Collections.fill(dlist, "way2testing");
System.out.println(dlist);
}
}

Output :-

maximum value 45
maximum value 5
Sorted Strings [Cha, Chandan, Chauhan]
Reversed Strings [Chauhan, Chandan, Cha]
[Chandan, Chauhan, Cha]
[way2testing, way2testing, way2testing]



No comments:

Post a comment