A collection — sometimes called a container — is simply an object that groups multiple elements into a single unit.
Collections are used to store, retrieve, manipulate, and communicate aggregate data.
If you have used the Java programming language — or just about any other programming language — you are already familiar with collections.
What Is a Collections Framework? A collections framework is a unified architecture for representing and manipulating collections. All collections frameworks contain the following:
Interfaces: These are abstract data types that represent collections. Interfaces allow collections to be manipulated independently of the details of their representation. In object-oriented languages, interfaces generally form a hierarchy.
Implementations: These are the concrete implementations of the collection interfaces. In essence, they are reusable data structures.
Algorithms: These are the methods that perform useful computations, such as searching and sorting, on objects that implement collection interfaces. The algorithms are said to be polymorphic: that is, the same method can be used on many different implementations of the appropriate collection interface. In essence, algorithms are reusable functionality.
Apart from the Java Collections Framework, the best-known examples of collections frameworks are the C++ Standard Template Library (STL) and Smalltalk's collection hierarchy.
Benefits of the Java Collections Framework
Reduces programming effort
Increases program speed and quality
Allowsinteroperability among unrelated APIs
Reduces effort to learn and to use new APIs
Reduces effort to design new APIs
Fosters software reuse
The core collection interfaces encapsulate different types of collections, which are shown in the figure below.
These interfaces allow collections to be manipulated independently of the details of their representation.
Core collection interfaces are the foundation of the Java Collections Framework. As you can see in the following figure, the core collection interfaces form a hierarchy.
Two interface trees, one starting with Collection and including Set, SortedSet, List, and Queue, and the other starting with Map and including SortedMap.
The core collection interfaces.
A Set is a special kind of Collection, a SortedSet is a special kind of Set, and so forth. Note also that the hierarchy consists of two distinct trees — a Map is not a true Collection.
Note that all the core collection interfaces are generic. For example, this is the declaration of the Collection interface.
public interface Collection...
The
To keep the number of core collection interfaces manageable, the Java platform doesn't provide separate interfaces for each variant of each collection type. (Such variants might include immutable, fixed-size, and append-only.)
Instead, the modification operations in each interface are designated optional — a given implementation may elect not to support all operations. If an unsupported operation is invoked, a collection throws an UnsupportedOperationException. Implementations are responsible for documenting which of the optional operations they support. All of the Java platform's general-purpose implementations support all of the optional operations.
The following list describes the core collection interfaces:
Collection — the root of the collection hierarchy. A collection represents a group of objects known as its elements.
Set — a collection that cannot contain duplicate elements.
List — an ordered collection (sometimes called a sequence). Lists can contain duplicate elements.
Queue — a collection used to hold multiple elements prior to processing. Besides basic Collection operations, a Queue provides additional insertion, extraction, and inspection operations. Queues typically, but do not necessarily, order elements in a FIFO (first-in, first-out) manner. Among the exceptions are priority queues, which order elements according to a supplied comparator or the elements' natural ordering. Whatever the ordering used, the head of the queue is the element that would be removed by a call to remove or poll. In a FIFO queue, all new elements are inserted at the tail of the queue. Other kinds of queues may use different placement rules. Every Queue implementation must specify its ordering properties.
Deque — a collection used to hold multiple elements prior to processing. Besides basic Collection operations, a Deque provides additional insertion, extraction, and inspection operations. Deques can be used both as FIFO (first-in, first-out) and LIFO (last-in, first-out). In a deque all new elements can be inserted, retrieved and removed at both ends.
Map — an object that maps keys to values. A Map cannot contain duplicate keys; each key can map to at most one value.
The last two core collection interfaces are merely sorted versions of Set and Map:
SortedSet — a Set that maintains its elements in ascending order.
SortedMap — a Map that maintains its mappings in ascending key order.
A Collection represents a group of objects known as its elements. The Collection interface is used to pass around collections of objects where maximum generality is desired.
import java.util.*;
public class HelloWorld{
public static void main(String []args){
Collection cars;
cars = new ArrayList();
cars.add("Volvo");
System.out.println(cars);
Collection digits;
digits = new ArrayList();
digits.add(1);
System.out.println(digits);
Collection sample;
sample = new ArrayList();
sample.add(true);
System.out.println(sample);
Collection f;
f = new ArrayList();
f.add(0.26f);
System.out.println(f);
Collection d;
d = new ArrayList();
d.add(32.5698);
System.out.println(d);
Collection l;
l = new ArrayList();
l.add(325489518L);
System.out.println(l);
}
}
Output:
[Volvo]
[1]
[true]
[0.26]
[32.5698]
[325489518]
The Collection interface contains methods that perform basic operations
import java.util.*;
public class HelloWorld{
public static void main(String []args){
Collection l;
l = new ArrayList();
l.add(325489518L);
System.out.println(l);
System.out.println(l.size());
System.out.println(l.isEmpty());
System.out.println(l.contains(325489518L));
System.out.println(l.contains(11L));
l.remove(325489518L);
}
}
Output:
[325489518]
1
false
true
false
true
Loop through the elements of an Collection ArrayList with a for loop, and use the size() method to specify how many times the loop should run
import java.util.*;
public class MyClass {
public static void main(String[] args) {
ArrayList cars;
cars = new ArrayList();
cars.add("Volvo");
cars.add("BMW");
cars.add("Ford");
cars.add("Mazda");
for (int i = 0; i < cars.size(); i++) {
System.out.println(cars.get(i));
}
}
}
Output:
Volvo
BMW
Ford
Mazda
You can also loop through an ArrayList with the for-each loop:
import java.util.*;
public class MyClass {
public static void main(String[] args) {
ArrayList cars = new ArrayList();
cars.add("Volvo");
cars.add("BMW");
cars.add("Ford");
cars.add("Mazda");
for (String i : cars) {
System.out.println(i);
}
}
}
Output:
Volvo
BMW
Ford
Mazda
‘Iterator’ is an interface which belongs to collection framework. It allows us to traverse the collection, access the data element and remove the data elements of the collection.
java.util package has public interface Iterator and contains three methods:
boolean hasNext(): It returns true if Iterator has more element to iterate.
Object next(): It returns the next element in the collection until the hasNext()method return true. This method throws ‘NoSuchElementException’ if there is no next element.
void remove(): It removes the current element in the collection. This method throws ‘IllegalStateException’ if this function is called before next( ) is invoked.
import java.io.*;
import java.util.*;
class Test {
public static void main(String[] args)
{
ArrayList list = new ArrayList();
list.add("A");
list.add("B");
list.add("C");
list.add("D");
list.add("E");
// Iterator to traverse the list
Iterator iterator = list.iterator();
System.out.println("List elements : ");
while (iterator.hasNext())
System.out.print(iterator.next() + " ");
System.out.println();
}
}
Output:
List elements :
A B C D E
Collection Interface Bulk Operations Bulk operations perform an operation on an entire Collection. The following are the bulk operations:
containsAll — returns true if the target Collection contains all of the elements in the specified Collection.
addAll — adds all of the elements in the specified Collection to the target Collection.
removeAll — removes from the target Collection all of its elements that are also contained in the specified Collection.
retainAll — removes from the target Collection all its elements that are not also contained in the specified Collection. That is, it retains only those elements in the target Collection that are also contained in the specified Collection.
clear — removes all elements from the Collection.
The addAll, removeAll, and retainAll methods all return true if the target Collection was modified in the process of executing the operation.
import java.util.*;
public class HelloWorld{
public static void main(String []args){
Collection cars;
cars = new ArrayList();
cars.add("volvo");
cars.add("ferrari");
Collection cars2;
cars2 = new ArrayList();
cars2.add("volvo");
cars2.add("ferrari");
cars2.add("fiat");
cars2.add("truck");
System.out.println(cars.containsAll(cars2));
cars2.addAll(cars);
System.out.println(cars2);
cars2.removeAll(cars);
System.out.println(cars2);
cars2.retainAll(cars);
System.out.println(cars2);
cars2.clear();
System.out.println(cars2);
}
}
Output:
false
[volvo, ferrari, fiat, truck, volvo, ferrari]
[fiat, truck]
[]
[]