In this article, we will discuss the difference between Collection and Collections in Java.
Java is well known for its comprehensive library, one of which is the Java Collections Framework. It includes interfaces and classes that are used to represent and manipulate collections of objects. Two terms that are often discussed when talking about this framework are Collection and Collections. They sound similar, but they are fundamentally different.
Collection - It is an Interface
The Collection is an interface in the Java Collections Framework.
It defines the basic methods that all collections will have, such as add(), remove(), size(), isEmpty(), iterator(), etc.
The Collection is essentially a group of individual objects represented as a single unit.
It acts as the root interface in the collection hierarchy and is located in java.util package.
Collection is more of a concept for storing data, rather than a tool for manipulating data.
Collection Interface Example
import java.util.ArrayList;
import java.util.Collection;
public class CollectionDemo {
public static void main(String[] args) {
Collection < String > fruitCollection = new ArrayList < > ();
fruitCollection.add("banana");
fruitCollection.add("apple");
fruitCollection.add("mango");
System.out.println(fruitCollection);
fruitCollection.remove("banana");
System.out.println(fruitCollection);
System.out.println(fruitCollection.contains("apple"));
fruitCollection.forEach((element) -> {
System.out.println(element);
});
fruitCollection.clear();
System.out.println(fruitCollection);
}
}
Output:
[banana, apple, mango]
[apple, mango]
true
apple
mango
[]
Collection <String> fruitCollection = new ArrayList<>();
Collections - It is a Utility Class
Collections Utility Class Example
import java.util.*;
public class Main {
public static void main(String[] args) {
List<String> list = new LinkedList<>();
list.add("element 2");
list.add("element 1");
list.add("element 4");
list.add("element 3");
// Sorts the specified list into ascending order, according to
// the natural ordering of its elements.
Collections.sort(list);
for (String str : list) {
System.out.println("sort elements in ascending order --" + str);
}
}
}
sort elements in ascending order --element 1
sort elements in ascending order --element 2
sort elements in ascending order --element 3
sort elements in ascending order --element 4
Comments
Post a Comment
Leave Comment