Collection Framework in Java

by | Dec 20, 2020 | Java

Home » Java » Collection Framework in Java

Introduction

Collections are groups of identifies that respond to a common stimulus. In Java, a Collection defines a group of memory locations that are bound together in architecture to give you space to store objects of the same type and perform operations on it. As Collections are groups of memory locations containing values, the collection can be searched and sorted. Data elements can be inserted at any position of the collection as well as deleted. The Collection can be separated into interfaces and classes. Sets, Lists, Queues, and Dequeues are part of the interface while ArrayList, Vector, LinkedList, PriorityQueue, HashSet, LinkedHashSet, and TreeSet are the different classes. To summarize it, collections are unique units of objects bound together in a group.

Collection Framework in Java

A framework in Java gives a brief description of the architecture of the program. It provides several classes and interfaces. The Collection Framework contains all the above-mentioned ready-made data structures and can be imported using the following sequence: import java.util.Collection;.

Example

We will create three collections namely a general array, a Vector, and a HashTable, and compare the various methods used to insert data into each. Finally, we will print random elements from the collections.

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

class SampleCollection
{
public static void main (String args [])
{
int arr[] = new int[] { 1, 2, 3, 4, 5};
Vector<Integer> v = new Vector();
HashTable <Integer, String> h = new HashTable();

v.addElement (20);
v.addElement (30);

h.put(22, “Hello”);
h.put(32, “World”);

System.out.println(arr[0]);
System.out.println(v.elementAt(0));
System.out.println(h.get(32));

}
}

OUTPUT

1
20
World

 

Advantages

  • Consistent API – The interfaces of the API are simple in nature. The classes (ArrayList, LinkedList, etc) try to implement the interfaces and thus have common methods.
  • Code Simplicity – As these collections are predefined and part of the framework, a developer need not worry about the nuances of the collections and can safely use it in programs.

Author

0 Comments

Submit a Comment

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.

Author