18CS644-NOTES Module 2
18CS644-NOTES Module 2
Collection Classes, Accessing a collection Via an Iterator, Storing User Defined Classes in
Collections, The Random Access Interface, Working With Maps, Comparators, The
Collection Algorithms, Why Generic Collections?, The legacy Classes and Interfaces, Parting
Thoughts on Collections.
VTUPulse.com
Collections Overview
✓ Collections framework was not a part of original Java release. Collections were added
to J2SE 1.2. Prior to Java 2.
✓ A collection in java is a framework that provides 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 performed by Java Collections.
✓ Java Collection simply 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).
✓ Framework in java means hierarchy of classes and interfaces.
✓ Collections framework is contained in java.util package.
✓ First, the frame work had to be high performance. The implementations for the
fundamental collections (dynamic arrays, linked lists, trees, and hash tables) are
VTUPulse.com
highly efficient. You seldom, if ever, need to code one of these “data engines”
manually.
✓ Second, the framework had to allow different types of collections to work in a
similar manner and with a high degree of interoperability.
✓ Third, extending and /or adapting a collection had to be easy. Toward this end, the
entire Collections Framework is built upon 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.
VTUPulse.com
✓ Earlier collections stored Object class references which meant any collection could
store any type of object.
✓ Hence there were chances of storing incompatible types in a collection, which could
result in run time mismatch. Hence Generics was introduced through which you can
explicitly state the type of object being stored.
✓ We have studied that Autoboxing converts primitive types into Wrapper class Objects.
As collections doesn't store primitive data types(stores only refrences), hence
Autoboxing facilitates the storing of primitive data types in collection by boxing it
into its wrapper type.
✓ for-each version of for loop can also be used for traversing each elementof a
collection.
✓ But this can only be used if we don't want to modify the contents of acollection
and we don't want any reverse access.
✓ for-each loop can cycle through any collection of object that implementsIterable
interface.
VTUPulse.com
public static void main(String[] args)
{
LinkedList< String> ls = new LinkedList< String>();
ls.add("a");
ls.add("b");
ls.add("c");
ls.add("d");
Output :a b c d
Collection Interfaces
Interface Description
VTUPulse.com
All these Interfaces give several methods which are defined by collectionsclasses which
implement these interfaces.
Collection
VTUPulse.com
2. Following are some of the commonly used methods in this interface.
Methods Description
VTUPulse.com
void clear()
Removes
collection.
total number of elements from the
4. Apart from methods of Collection Interface, it adds following methods ofits own.
Methods Description
VTUPulse.com
Object get( int index )
1. This interface defines a Set. It extends Collection interface and doesn'tallow insertion
of duplicate elements. It's general declaration is,
2. It doesn't define any method of its own. It has two sub interfaces,
SortedSet and NavigableSet.
3. SortedSet interface extends Set interface and arranges added elementsin an ascending
order.
4. NavigabeSet interface extends SortedSet interface, and allows retrievalof elements
based on the closest match to a given value or values.
1. It extends collection interface and defines behaviour of queue, that isfirst-in, first-
VTUPulse.com
out. It's general declaration is,
2. There are couple of new and interesting methods added by this interface.Some of
them are mentioned in below table.
Methods Description
✓ There are some standard classes that implements Collection interface.Some of the
classes provide full implementations that can be used as it is.
✓ Others are an abstract class, which provides skeletal implementationsthat can be used
as a starting point for creating concrete collections.
Class Description
VTUPulse.com
AbstractSequentialList
sequential rather than random access of its elements.
Note:
1. To use any Collection class in your program, you need to import it in your program. It
is contained inside java.util package.
2. Whenever you print any Collection class, it gets printed inside the square brackets [ ].
ArrayList class
✓ Simple arrays have fixed size i.e it can store fixed number of elements. But,
sometimes you may not know beforehand about the number of elements that you are
VTUPulse.com
going to store in your array.
✓ In such situations, we can use an ArrayList, which is an array whose size can increase
or decrease dynamically.
import java.util.*
class Test
{
public static void main(String[] args)
{
ArrayList< String> al = new ArrayList< String>();
}
VTUPulse.com
al.add("ab");
al.add("bc");
al.add("cd");
system.out.println(al);
}
Output :
[ab,bc,cd]
al.add(1,"A2");
VTUPulse.com
System.out.println(" updated Contents of al:"+al);
al1.retainAll(al2);
System.out.println("Contents of al1 using reatain all: " + al1);
al1.removeAll(al2); System.out.println("Contents of
al1: " + al1);
Output
VTUPulse.com
Size of al after deletions: 5 Contents of al:
[C, A2, E, B, D]
Contents of al1: [mahesh, Vijay, pramod]
Contents of al1: [mahesh, Vijay, pramod, pramod, naveen, goutham] Contents of al1
using reatain all: [pramod, pramod, naveen, goutham]Contents of al1: []
✓ toArray() method is used to get an array containing all the contents ofthe
ArrayList.
✓ Following are some reasons for why you can need to obtain an array fromyour
ArrayList:
class ArrayListToArray {
VTUPulse.com
al.toArray(ia);
int sum = 0;
}
}
Output
Sum is: 10
In the above mentioned example we are storing only string object in ArrayList collection. But
You can store any type of object, including object of class that you create in Collection
classes.
class Student
{
int rollno;
String name;
int age;
Student(int rollno,String name,int age)
{
this.rollno=rollno;
this.name=name;
this.age=age;
}
}
VTUPulse.com
public static void main(String[] args)
{
// TODO Auto-generated method stub
//creating arraylist
ArrayList<Student> al=new ArrayList<Student>();
al.add(s1); //adding Student class object al.add(s2);
al.add(s3);
System.out.println(al);
LinkedList class
VTUPulse.com
2. LinkedList has two constructors.
1. LinkedList() //It creates an empty LinkedList
2. LinkedList( Collection C ) //It creates a LinkedList that isinitialized
with elements of the Collection c
3. It can be used as List, stack or Queue as it implements all the relatedinterfaces.
4. They are dynamic in nature i.e it allocates memory when required. Therefore
insertion and deletion operations can be easily implemented.
5. It can contain duplicate elements and it is not synchronized.
6. Reverse Traversing is difficult in linked list.
7. In LinkedList, manipulation is fast because no shifting needs to beoccurred.
ll.addLast("Z");
ll.addFirst("A");
ll.add(1, "A2");
VTUPulse.com
// Remove elements from the linked list.
ll.remove("F");
ll.remove(2);
ll.removeFirst();
ll.removeLast();
Output:
✓ ArrayList and LinkedList are the Collection classes, and both of them implements
the List interface.
✓ The ArrayList class creates the list which is internally stored in a dynamic array that
grows or shrinks in size as the elements are added or deleted from it.
VTUPulse.com
✓ LinkedList also creates the list which is internally stored in a DoublyLinked List.
✓ Both the classes are used to store the elements in the list, but the major difference
between both the classes is that ArrayList allows random access to the elements in the
list as it operates on an index-based data structure.
✓ On the other hand, the LinkedList does not allow random access as it does not have
indexes to access elements directly, it has to traverse the list to retrieve or access an
element from the list.
HashSet class
VTUPulse.com
1. HashSet() //This creates an empty HashSet
import java.util.*;
public class HashSetDemo
{
public static void main(String[] args)
{
// TODO Auto-generated method stub HashSet<
String> hs = new HashSet< String>();hs.add("B");
hs.add("A");
hs.add("D");
hs.add("E");
hs.add("C");
hs.add("F");
hs.add("F");
System.out.println(hs);
VTUPulse.com
HashSet< Integer> hs1 = new HashSet< Integer>();
hs1.add(10);
hs1.add(677);
hs1.add(5);
hs1.add(4);
hs1.add(4);
System.out.println(hs1);
}
Output:
[D, E, F, A, B, C]
[4, 5, 677, 10]
LinkedHashSet Class
import java.util.*;
public class LinkedHashSetDemo
{
public static void main(String[] args)
{
LinkedHashSet< String> hs = new LinkedHashSet< String>();hs.add("B");
hs.add("A");
hs.add("D");
hs.add("E");
VTUPulse.com hs.add("C");
hs.add("F");
System.out.println(hs);
LinkedHashSet< Integer> hs1 = new LinkedHashSet< Integer>();
hs1.add(10);
hs1.add(677);
hs1.add(5);
hs1.add(4);
hs1.add(4);
System.out.println(hs1);
}
}
Output :
[B, A, D, E, C, F]
[10, 677, 5, 4]
Questions
1. What is collection in java? Mention some of the recent changes to
Collections.
2. List and give brief description on Java Collection Interfaces and Classes.
VTUPulse.com