UNIT 8
UNIT 8
8: JAVA COLLECTIONS
Contents
8.0. Aims and Objectives
8.1. The Java Collections Framework
8.2. Collections Interfaces
8.3.Summary
8.3.Summary
8.4. Model Examination Questions
This unit discusses java collections frameworks and multiple interfaces, array lists, linked
lists, vectors and classes.
After you have studied this unit, you will be able to:
1
8.1. THE JAVA COLLECTIONS FRAMEWORK
• Interfaces
• Classes
• Algorithm
Interfaces: Interface in Java refers to the abstract data types. They allow Java collections
to be manipulated independently from the details of their representation. Also, they form a
hierarchy in object-oriented programming languages. 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.
Classes: Classes in Java are the implementation of the collection interface. It basically
refers to the data structures that are used again and again. These are the concrete
implementations of the collection interfaces. In essence, they are reusable data structures.
Algorithm: Algorithm refers to the methods which are used to perform operations such as
searching and sorting, on objects that implement collection interfaces. Algorithms are
polymorphic in nature as the same method can be used to take many forms or you can say
perform different implementations of the Java collection interface. 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.
2
The Java collection framework provides the developers to access prepackaged data
structures as well as algorithms to manipulate data.
The collections framework was designed to meet several goals, such as:
Towards this end, the entire collections framework is designed around a set of standard
interfaces. Several standard implementations such as LinkedList, HashSet, and TreeSet,
of these interfaces are provided that you may use as-is and you may also implement your
own collection, if you choose.
In addition to collections, the framework defines several map interfaces and classes. Maps
store key/value pairs. Although maps are not collections in the proper use of the term, but
they are fully integrated with collections.
The Collection in Java is a framework that provides an architecture to store and manipulate
the group of objects. All the operations that you perform on a data such as searching,
sorting, insertion, manipulation, deletion, etc. can be achieved by Java Collections. Java
Collection means a single unit of objects. Java Collection framework provides many
interfaces (Set, List, Queue, Deque, etc.) and classes (ArrayList, Vector, LinkedList,
PriorityQueue, HashSet, LinkedHashSet, TreeSet, etc.). A Collection represents a single unit
of objects, i.e., a group.
3
Check your progress-1
1. List and explain java collection framework?
_________________________________________________________________________________________________
_________________________________________________________________________________________________
Iterator interface: Iterator is an interface that iterates the elements. It is used to traverse
the list and modify the elements. Iterator interface has three methods which are mentioned
below:
1. public boolean hasNext() – This method returns true if iterator has more
elements.
4
2. public object next() – It returns the element and moves the cursor pointer to the
next element.
3. public void remove() – This method removes the last elements returned by the
iterator.
There are three components that extend the collection interface i.e List, Queue and Sets.
Let’s learn about them in detail:
1. ArrayList
2. LinkedList
3. Vectors
Let’s go into detail on each one of them:
1. Array list: ArrayList is the implementation of List Interface where the elements can be
dynamically added or removed from the list. Also, the size of the list is increased
dynamically if the elements are added more than the initial size.
Syntax:
import java.util.*;
class TestJavaCollection1{
public static void main (String args []) {
ArrayList<String> list=new ArrayList<String>(); //Creating arraylist
list.add("Hello"); //Adding object in arraylist
list.add("World");
list.add("Java"); OUTPUT Example
list.add("OOP"); Hello
//Traversing list through Iterator World
Iterator itr=list.iterator(); Java
while(itr.hasNext()){ OOP
System.out.println(itr.next()); }} }
5
2. Linked List: Linked List is a sequence of links which contains items. Each link contains
a connection to another link.
Java Linked List class uses two types of Linked list to store the elements:
Singly Linked List: In a singly Linked list each node in this list stores the data of the node
and a pointer or reference to the next node in the list.
Doubly Linked List: In a doubly Linked list, it has two references, one to the next node and
another to previous node. Example:
import java.util.*;
public class TestJavaCollection2{
public static void main(String args[]){
LinkedList<String> al=new LinkedList<String>();
al.add("Hello");
al.add("World");
al.add("Java"); OUTPUT
al.add("OOP"); Hello
Iterator<String> itr=al.iterator(); World
while(itr.hasNext()){ Java
System.out.println(itr.next()); OOP
}
}
}
3. Vectors: Vectors are similar to arrays, where the elements of the vector object can be
accessed via an index into the vector. Vector implements a dynamic array. Also, the
vector is not limited to a specific size, it can shrink or grow automatically whenever
required. It is similar to ArrayList, but with two differences:
• Vector is synchronized.
6
• Vector contains many legacy methods that are not part of the collections
framework.
Example:
import java.util.*;
public class TestJavaCollection3{
public static void main(String args[]){ OUTPUT
Vector<String> v=new Vector<String>(); Hello
v.add("Hello");
World
v.add("World");
Java
v.add("Java");
OOP
v.add("OOP");
Iterator<String> itr=v.iterator();
while(itr.hasNext()){
System.out.println(itr.next());
}
}
}
Queue in Java follows a FIFO approach i.e. it orders the elements in First In First Out
manner. In a queue, the first element is removed first and last element is removed in the
end. Each basic method exists in two forms: one throws an exception if the operation fails,
the other returns a special value.
Also, priority queue implements Queue interface. The elements of the priority queue are
ordered according to their natural ordering, or by a Comparator provided at the queue
construction time. The head of this queue is the least element with respect to the specified
ordering.
Java Collections: Sets
A Set refers to a collection that cannot contain duplicate elements. It is mainly used to
model the mathematical set abstraction. Set has its implementation in various classes such
as HashSet, TreeSetand LinkedHashSet.
7
Let’s go into detail on each one of them:
HashSet: Java HashSet class creates a collection that use a hash table for
storage. Hashset only contain unique elements and it inherits the AbstractSet class and
implements Set interface. Also, it uses a mechanism hashing to store the elements.
Linked Hashset: Java LinkedHashSet class is a Hash table and Linked list implementation
of the set interface. It contains only unique elements like HashSet. Linked HashSet also
provides all optional set operations and maintains insertion order.
TreeSet: TreeSet class implements the Set interface that uses a tree for storage. The objects
of this class are stored in the ascending order. Also, it inherits AbstractSet class and
implements NavigableSet interface. It contains only unique elements like HashSet. In
TreeSet class, access and retrieval time are faster.
8.3. SUMMARY
Collections are objects whose sole purpose is to store other objects, like arrays. Unlike
arrays, however, collections have convenience methods to, say, return a portion of the
original collection. A drawback of collections is that they can't hold primitives. (They can,
however, hold wrappers, like java.lang.Integer .)
8
All collection objects ultimately implement the java.util.Collection interface. However, few
if any implement the interface directly. There are multiple sub-interfaces of Collection that
differently.)
Most implementations of the Collection interface are in java.util . Exceptions will be noted
9
Frameworks in Java provides readymade architecture, it represents a set of classes and
interfaces and it is optional. The Collection framework represents a unified architecture for
storing and manipulating a group of objects. It has:
I: True/False questions
1. In a queue, the first element is removed first and last element is removed in the
end.
2. A drawback of collections is that they can't hold primitives.
3. The Java collection framework provides the developers to access prepackaged
data structures as well as algorithms to manipulate data.
4. Vector is not limited to a specific size; it can shrink or grow automatically
whenever required.
II: Short Answer Questions
10