×

Collection Programs in Java

Collection Programs in Java

Collection in Java provides a way to manipulate or store a group of objects. Each object in a collection is called element. Collection programs in Java mainly deals with the Java collection framework that provides various interfaces, classes that is used to implement different types of data structures and algorithms. For example, the implementation of doubly linked list is done by the class LinkedList of the collection framework.

Interfaces of Collection Framework

There are various interfaces that are integral part of the Collection Framework. Some of the interfaces that form the core of the Collection Framework are:

1) Iterable Interface: It is the root interface of collection framework hierarchy. This interface provides iterators for the collection elements. These iterators are very handy when traversal of elements is required.

2) Collection Interface: It extends the Iterable interface. Other interfaces, List, Set, and Queue extends the collection interface. Collection interface renders all the basic methods that are required by a collection element. In collection framework, no class directly implements this interface. This framework provides the foundation upon which the collection framework relies a lot.

3) List Interface: It is used to provide elements in ordered manner. Using this interface, one can add, remove, and update elements from the list. Elements can be inserted or accessed by their position in the list. Using List interface, it is possible to create dynamic lists, i.e., those lists whose size can be update during run-time. LinkedList, ArrayList, Vector, Stack are the classes that implement the List interface.

4) Set Interface: Set interface is similar to sets that we have learnt in Mathematics. Similar to mathematics, duplicate elements are not allowed in Set interface. TreeSet and LinkedHashSet are the classes that implement this interface.

5) Queue Interface: The queue interface provides the features of queue data structure. This means, elements of the classes that implement Queue Interface, are stored in First In First Out (FIFO) manner. Classes that implement this interface are ArrayDeque, PriorityQueue.

6) Map Interface: It does not extend the Iterable interface. This interface is another root of the collection framework. Objects of the class implementing the Map interface always store association between keys and values, i.e. it maintains key/ value pair. Note that the key, in the key/ value pair, has to be unique. However, duplicates values are allowed. TreeMap and HashMap are the classes that provide the implementation of the Map interface.

Methods of the Collection Interface

The Collection Interface provides core methods that all collections will have.

MethodsDescription
public boolean add(Object o)for adding an element
public static boolean addAll(Collection c)Add the collection c to the given collection
public boolean remove(Object o)remove the object o.
public boolean removeAll(Collection c)Remove the collection C from the given collection
public boolean retainAll(Collection c)All the elements of the collection c get retained, while others get deleted.
public int size()returns size of the collection
public void clear()remove all elements from the collection
public boolean contains(Object o)Checks if the object o is present in the collection or not.
public boolean containsAll(Collection c)Checks whether the collection c is present in the collection or not.
public boolean isEmpty()Checks if the collection is empty or not.
public Iterator iterator()Returns an iterator for the collection.
public Object[] to arrayConverts the collection into array.
Object[] toArray(Object arr[])Returns an array whose type matches with the array arr.
public int hashCode()for returning the hash code number of the collection.
public boolean equals(Object o)compares the object o with the object that invokes this method.

Note: The last two methods are of the Object class.

Significance of the Collection Framework

1) This framework provides various algorithm and data structures that can be used directly in the code. Thus, we do not need to implement those data structures or algorithms manually. For example, for storing unique element only set interface can be use. For storing elements in ordered way, array list or linked list can be used.

2) Collection framework is highly optimized. Thus, the code written using this framework is highly efficient.

Let’s see an example of Collection.

CollectionExample.java

 import java.util.*;  
class CollectionExample.java
{  
public static void main(String args[]){  
ArrayList<String> list=new ArrayList<String>();//Creating arraylist  
list.add("Norway");//Adding object in arraylist  
list.add("Atlanta");  
list.add("Czech Republic");  
list.add("Santa Clara");  
//Traversing list through Iterator  
Iterator itr=list.iterator();  
while(itr.hasNext()){  
System.out.println(itr.next());  
}  
}  
}   

Output:

 Norway
Atlanta
Czech Republic
Santa Calara 

Related Topics

Multiple Inheritance Programs in Java

A component of the object-oriented notion known as multiple inheritances allows a class to inherit properties from multiple parent classes. When methods that have the same signature are present in...

4 minutes read.

Stone Game in Java

In this tutorial, we will learn to design a stone game in Java. First of all, we will understand what is this game all about. We will grasp it through...

9 minutes read.

Java Interface Lock

A synchronisation method called the Lock interface is available as of JDK 1.5. It is comparable to a synchronised block but more complex and versatile. The package java.util.concurrent contains the...

4 minutes read.

Java InetAddress class

InetAddress class The InetAddress class refers to the IP address, both IPv4 and IPv6.An instance of an InetAddress consists of an IP address and possibly its corresponding hostname. It provides a method to get the...

9 minutes read.

Java Math sinh() Method

The sinh() method of Java Math class returns the hyperbolic sine of the specified double value. Syntax: public static double sinh(double x) Parameters: The parameter ‘a’ represents the number whose hyperbolic sine is to...

2 minutes read.

ConcurrentSkipListSet in Java

ConcurrentSkipListSet is a class that is a part of collection framework in Java.It has been available since Java version 1.6. ConcurrentSkipListSet  is a scalable concurrent NavigableSet implementation based on a ConcurrentSkipListMap.The...

16 minutes read.

Java Private keyword

A Java access modifier is a private keyword. It can be used to inner classes, methods, and variables. It is the type of access modifier that is most constrained. Privately declared...

4 minutes read.

Java inheritance with Example

Java inheritance Java inheritance is a mechanism in which a child object acquires all the properties and behaviors of a parent object. It helps in reusing the code and establishes...

7 minutes read.

Java Hello World

Let’s start by writing a simple program that prints “Hello World” to the output window. Write the program into any text editor or IDE (Eclipse, Netbeans, etc.) and save the file with the...

2 minutes read.

Cosmic Superclass in Java

The parent class of all Java classes is the Object class. The Java Object class is the parent of all Java classes, whether directly or indirectly. The Object class is...

6 minutes read.

LCM Program in Java

LCM Program in Java The LCM program in Java outputs the LCM of the given numbers. In Arithmetic, the lowest common multiple, least common multiple or smallest common multiple of the...

6 minutes read.

Java String Concatenation

Java String Concatenation Java programming provide a way to combine multiple strings into a single string. It is called as String Concatenation. There are different ways to concatenate two or more...

4 minutes read.

Java Single Linkedlist

Like arrays, linked lists are a type of linear data structure. Unlike arrays, which store each element in the same location, linked lists employ pointers to connect the elements together. In...

25 minutes read.

Types of Sockets in Java

The fundamental idea behind Java's networking capability is the socket. Early in the 1980s, the Berkeley UNIX 4.2BSD version included the socket paradigm. Berkeley socket is the term employed as...

9 minutes read.

Java Externalization

What is Externalization in Java? Externalization is a concept that is advanced to serialization. Serialization is a concept where we can transfer an object from our JVM ( Java virtual machine...

3 minutes read.

GCD of Different SubSequences in Java

The positive numbers are provided in an array called inArr. The aim is to determine the number of distinct GCDs (Greatest Common Divisors) in each subsequence present in the input...

4 minutes read.

How to compare dates in Java

Introduction: In Java, dates can be compared using a similar interface's compareTo() technique. This method returns 'zero' if each date is the same, returns a rate "more than 0" if...

6 minutes read.

Java Math ceil() Method

The ceil() method of Math class returns the smallest double value which is closest to negative infinity and is greater than or equal to the argument. Syntax: public static double ceil(double a) Parameters: The...

2 minutes read.

Concurrent Modification Exception In Java

When an object is attempted to be updated concurrently when it is not allowed, the ConcurrentModificationException arises. This error typically occurs while using Java Collection classes. When another thread is iterating...

5 minutes read.

Access specifiers in Java

What are access specifiers in Java? Access specifiers in Java are used to determine whether other classes can use a particular field or invoke a particular method. Access specifiers mainly specify...

7 minutes read.