Collections in Java
Collections
• Collections 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 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).
• What is Collection in java?
• Collection represents a single unit of objects i.e. a group.
What is framework in java?
• provides readymade architecture.
• represents set of classes and interface.
• is optional.
What is Collection framework?
• Collection framework represents a unified architecture
for storing and manipulating group of objects. It has:
• Interfaces and its implementations i.e. classes
• Algorithm
Hierarchy of Collection Framework
The java.util package contains all the classes and interfaces for Collection framework.
Iterator interface
• Iterator interface provides the facility of iterating the elements in
forward direction only.Methods of Iterator interface
• There are only three methods in the Iterator interface. They are:
– public boolean hasNext() it returns true if iterator has more
elements.
– public object next() it returns the element and moves the cursor
pointer to the next element.
– public void remove() it removes the last elements returned by the
iterator. It is rarely used.
•
Java ArrayList class
• Java ArrayList class uses a dynamic array for storing the elements.It
extends AbstractList class and implements List interface.
• Java ArrayList class can contain duplicate elements.
• Java ArrayList class maintains insertion order.
• Java ArrayList class is non synchronized.
• Java ArrayList allows random access because array works at the index
basis.
• In Java ArrayList class, manipulation is slow because a lot of shifting needs
to be occurred if any element is removed from the array list.
•
Example of Java ArrayList class
import java.util.*;
class TestCollection1{
public static void main(String args[]){
ArrayList<String> al=new ArrayList<String>();//creating arraylist
al.add("Ravi");//adding object in arraylist
al.add("Vijay");
al.add("Ravi");
al.add("Ajay");
Iterator itr=al.iterator();//getting Iterator from arraylist to traverse elements
while(itr.hasNext()){
System.out.println(itr.next());
}
}
}
Ravi Vijay Ravi Ajay
Java LinkedList class
• Java LinkedList class uses doubly linked list to store the elements. It
extends the AbstractList class and implements List and Deque
interfaces.
• Java LinkedList class can contain duplicate elements.
• Java LinkedList class maintains insertion order.
• Java LinkedList class is non synchronized.
• In Java LinkedList class, manipulation is fast because no shifting
needs to be occurred.
• Java LinkedList class can be used as list, stack or queue.
Java LinkedList Example
import java.util.*;
public class TestCollection7{
public static void main(String args[]){
LinkedList<String> al=new LinkedList<String>();
al.add("Ravi");
al.add("Vijay");
al.add("Ravi");
al.add("Ajay");
Iterator<String> itr=al.iterator();
while(itr.hasNext()){
System.out.println(itr.next());
}
}
}
Output:Ravi Vijay Ravi Ajay
Java List Interface
• List Interface is the subinterface of Collection.It
contains methods to insert and delete elements in
index basis.It is a factory of ListIterator interface.
• Commonly used methods of List Interface:
– public void add(int index,Object element);
– public boolean addAll(int index,Collection c);
– public object get(int Index position);
– public object set(int index,Object element);
– public object remove(int index);
– public ListIterator listIterator();
– public ListIterator listIterator(int i);
Java ListIterator Interface
• ListIterator Interface is used to traverse the
element in backward and forward direction.
• Commonly used methods of ListIterator
Interface:
– public boolean hasNext();
– public Object next();
– public boolean hasPrevious();
– public Object previous();
Example of ListIterator Interface:
import java.util.*;
public class TestCollection8{
public static void main(String args[]){
ArrayList<String> al=new ArrayList<String>();
al.add("Amit");
al.add("Vijay");
al.add("Kumar");
al.add(1,"Sachin");
System.out.println("element at 2nd position: "+al.get(2));
ListIterator<String> itr=al.listIterator();
System.out.println("traversing elements in forward direction...");
while(itr.hasNext()){
System.out.println(itr.next());
}
System.out.println("traversing elements in backward direction...");
while(itr.hasPrevious()){
System.out.println(itr.previous());
}
}
}
Output:
element at 2nd position: Vijay
traversing elements in forward direction...
Amit Sachin Vijay Kumar
traversing elements in backward direction...
Kumar Vijay Sachin Amit
Map Interface
• The Map interface maps unique keys to values. A key is an object
that you use to retrieve a value at a later date.
• Given a key and a value, you can store the value in a Map object.
After the value is stored, you can retrieve it by using its key.
• Several methods throw a NoSuchElementException when no items
exist in the invoking map.
• A ClassCastException is thrown when an object is incompatible with
the elements in a map.
• A NullPointerException is thrown if an attempt is made to use a null
object and null is not allowed in the map.
• An UnsupportedOperationException is thrown when an attempt is
made to change an unmodifiable map.
Example:
import java.util.*;
public class CollectionsDemo {
public static void main(String[] args) {
Map m1 = new HashMap();
m1.put("Zara", "8");
m1.put("Mahnaz", "31");
m1.put("Ayan", "12");
m1.put("Daisy", "14");
System.out.println();
System.out.println(" Map Elements");
System.out.print("\t" + m1);
}
}
ap Elements {Mahnaz=31, Ayan=12, Daisy=14, Zara=8}
Comparator interface
• Comparator interface is used to order the objects of user-defined class.
• This interface is found in java.util package and contains 2 methods
compare(Object obj1,Object obj2) and equals(Object element).
• It provides multiple sorting sequence i.e. you can sort the elements based
on any data member. For instance it may be on rollno, name, age or
anything else.
• Syntax of compare method
– public int compare(Object obj1,Object obj2)
compares the first object with second object.
import java.util.*;
import java.io.*;
class Simple{
public static void main(String args[]){
ArrayList al=new ArrayList();
al.add(new Student(101,"Vijay",23));
al.add(new Student(106,"Ajay",27));
al.add(new Student(105,"Jai",21));
System.out.println("Sorting by Name...");
Collections.sort(al,new NameComparator());
Iterator itr=al.iterator();
while(itr.hasNext()){
Student st=(Student)itr.next();
System.out.println(st.rollno+" "+st.name+" "+st.age);
}
System.out.println("sorting by age...");
Collections.sort(al,new AgeComparator());
Iterator itr2=al.iterator();
while(itr2.hasNext()){
Student st=(Student)itr2.next();
System.out.println(st.rollno+" "+st.name+" "+st.age);
}
}
}
Output:
Sorting by Name...
106 Ajay 27
105 Jai 21
101 Vijay 23
Sorting by age...
105 Jai 21
101 Vijay 23
106 Ajay 27