COLLECTIONS IN JAVA Lecture #10
1
A Collection in java is a
framework that provides an
architecture to store and
manipulate the group of
objects.
All the operations that you
COLLECTION perform on a data such as
searching, sorting, insertion,
IN JAVA manipulation, deletion etc.
can be performed by Java
Collection.
Java Collection deals
with objects only.
2
WHAT IS A FRAMEWORK IN JAVA?
• provides readymade architecture.
• represents set of classes and interfaces.
• is optional.
3
JAVA COLLECTIONS
•The Java collections framework gives the programmer
access to prepackaged data structures as well as to
algorithms for manipulating them.
•A collection is an object that can hold references to other
objects.
•The collection interfaces declare the operations that can
be performed on each type of collection.
•The classes and interfaces of the collections framework
are in package [Link].
4
WHAT IS COLLECTION FRAMEWORK?
• Java Collection framework provides
– interfaces (Set, List, Queue, Deque etc.)
– classes (ArrayList, Vector, LinkedList, PriorityQueue,
HashSet, LinkedHashSet, TreeSet etc).
– Algorithms (sorting, binary search, …)
5
HIERARCHY OF COLLECTION FRAMEWORK
6
COLLECTION INTERFACES
The collections framework defines several interfaces. This section
provides an overview of each interface
7
COLLECTION INTERFACES (CONT.)
8
METHODS OF COLLECTION INTERFACE
No. Method Description
1 public boolean add(Object element) is used to insert an element in
this collection.
2 public boolean addAll(Collection c) is used to insert the specified
collection elements in the
invoking collection.
3 public boolean remove(Object element) is used to delete an element
from this collection.
4 public boolean removeAll(Collection c) is used to delete all the
elements of specified collection
from the invoking collection.
9
5 public boolean is used to delete all the
retainAll(Collection c) elements of invoking
collection except the
specified collection.
6 public int size() return the total number of
elements in the collection.
7 public void clear() removes the total no of
element from the collection.
8 public boolean contains(Object is used to search an element.
element)
10
9 public Object[] toArray() converts collection into
array.
10 public boolean isEmpty() checks if collection is
empty.
11 public boolean equals(Object element) matches two collection.
11
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 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.
12
ARRAYLIST CONSTRUCTORS
ArrayList has the 3 constructors shown here:
❑ArrayList ( )
empty ArrayList
❑ArrayList (Collection c)
ArrayList initialized with the elements of another collection c
❑ArrayList (int capacity)
builds an ArrayList that has the specified initial capacity. The
capacity is the size of the underlying array that is used to
store the elements.
The capacity grows automatically as elements are added to an
ArrayList.
13
METHODS OF ARRAYLIST
No. Method Description
1 public void add (int index, Object elem) is used to insert an element
obj in the array list at the
indicated index.
2 public boolean addAll (int index, is used to insert all the
Collection c) elements of c in the invoking
array list at the indicated
index. Any previously existed
elements are shifted up.
3 public Object get(int index) Returns the object stored at
the specified index within the
array list.
4 public int indexOf (Object obj) Returns the first (last)
occurrence of the element obj
at the array list. If the element
public int lastIndexOf (Object obj) is not exist it returns -1.
14
5 public Object remove (int index) is used to delete the
element at position index
from the invoking array list.
6 public Object set(int index, Object Assigns obj to the location
obj) specified by index within the
invoking list. Returns the old
value.
7 public List subList (int start, int Returns a list containing the
end) elements from start to
end-1 in the invoking list.
8 public void trimToSize() Reduces the size of the
array list to be precisely as
large as the number of
items it is currently holding.
9 public void ensureCapacity (int Increases the capacity of the
cap) array list manually to cap to
prevent several re-allcations
that costs time.
15
COMPARISON BETWEEN ARRAY AND ARRAYLIST
array ArrayList
Creation int a [] = new int [10]; ArrayList al = new
ArrayList ();
Inserting data at
the end
Inserting data
anywhere
Deleting data
Appending data
from other source
Displaying data for (int x: a) [Link] (al);
[Link] (x); 16
GENERIC ARRAYLIST
▪Java collection framework was non-generic before
JDK 1.5.
▪Java new generic collection allows you to have only
one type of object in collection. Now it is type-safe so
typecasting is not required at run time.
▪In generic collection, we specify the type in angular
braces. Now ArrayList is forced to have only
specified type of objects in it. If you try to add
another type of object, it gives compile time
error.
17
❑The old non-generic example of creating java collection.
ArrayList al=new ArrayList();
❑The new generic example of creating java collection.
ArrayList<String> al=new ArrayList<String>();
18
ADVANTAGE OF JAVA GENERICS
There are mainly 3 advantages of generics.:
1) Type-safety :
We can hold only a single type of objects in generics. It doesn’t allow to store other objects.
2) Type casting is not required:
There is no need to typecast the object. Before Generics, we need to type cast. For example:
ArrayList s = new ArrayList(); [Link]("hello"); String x = (String) [Link](0);//typecasting
After Generics, we don't need to typecast the object.
ArrayList<String> s = new ArrayList<String>(); [Link]("hello"); String x = [Link](0);
3) Compile-Time Checking:
It is checked at compile time so problem will not occur at runtime. The good
programming strategy says it is far better to handle the problem at compile time
than runtime.
ArrayList<String> s = new ArrayList<String>();
[Link]("hello");
[Link](32); //Compile Time Error 19
EXAMPLE
import [Link].*;
class TestGenerics1{
public static void main(String args[]) {
ArrayList<String> list=new ArrayList <String> ();
[Link](“abcd");
[Link](“xyz");
[Link](1, “uvw”);
//[Link](32); //compile time error
String s=[Link](1);
//type casting is not required
[Link]("element is: "+s);
20
[Link](list); } }
IMPORTANT NOTES
1. You can create your own generic class that can refer to any type T.
class MyGen<T>
{
T obj;
void add(T obj){[Link]=obj;}
T get(){return obj;}
}
To use this class; specify the actual type at the creation of the object
MyGen<Integer> m=new MyGen<Integer>();
[Link](2);
//[Link](“abcd");//Compile time error
[Link]([Link]());
MyGen <Student> st = new MyGen<Student>();
[Link](new Student ( , , , ) ); 21
2. Like generic class, you can create generic method that can accept
any type of argument.
public class TestGenerics {
public static < E > void printArray (E[ ] arr) {
for ( E element : arr)
[Link](element );
[Link]();
}
public static void main( String args[] ) {
Integer[ ] intArray = { 10, 20, 30, 40, 50 };
Character[ ] charArray = { 'J', 'A', 'V', 'A', 'L', 'E', 'C', 'T', ‘.' };
[Link]( "Printing Integer Array" );
printArray( intArray );
[Link]( "Printing Character Array" );
printArray( charArray );
}
}
22
THE COLLECTIONS ALGORITHMS
Collections class provides static methods for some
ready-made algorithms the could be used for any
collection.
For example, Collections class provides methods
for sorting the elements of List type elements.
23
METHODS OF CLASS COLLECTIONS
No. Method
1 public static int binarySearch (List list, Object value)
2 public static int binarySearch (List list, Object value, Comparator c)
3 public static void copy (List to, List from)
4 public static boolean disjoint (Collection a, Collection b)
5 public static void fill (List s, Object obj)
6 public static int frequency (Collection c, Object obj)
7 public static int indexOfSubList (List s, List sub)
24
No. Method
8 public static Object max (Collection cl)
9 public static Object max (Collection cl, Comparator c)
10 public static Object min (Collection cl)
11 public static Object min (Collection cl, Comparator c)
12 public static boolean replaceAll (List s, Object old, Object new)
13 public static void reverse (List s)
14 public static void rotate (List s, int n)
15 public static void sort (List s)
16 public static void sort (List s, Comparator c)
17 public static void swap (List s, int index1, int index2)
25
EXAMPLE
ArrayList<String> list=new ArrayList<String>();
[Link](“abcd");
[Link](“xyz");
[Link](“uvw”);
[Link](“abcf”);
String max = [Link](list);
[Link] (list);
[Link] (list);
[Link] (list,2);
26
COMPARATOR INTERFACE
❑Comparator defines precisely what “sorted order” means.
❑By default, classes store their elements by using what Java
refers to as “natural ordering,” which is usually the ordering
that you would expect (A before B, 1 before 2, and so
forth).
❑If you want to order elements a different way, then specify
a Comparator when you construct the set or map. Doing so
gives you the ability to govern precisely how elements are
stored within sorted collections and maps.
27
COMPARATOR INTERFACE (CONT.)
Comparator is a generic interface that has this declaration:
interface Comparator <T>
The Comparator interface defines two methods: compare( ) and equals( ).
The compare( ) method, compares two elements for order:
int compare(T obj1, T obj2)
Where obj1 and obj2 are the objects to be compared.
Normally, this method returns zero if the objects are equal. It returns a positive value
if obj1 is greater than obj2. Otherwise, a negative value is returned. The method can
throw a ClassCastException if the types of the objects are not compatible for
comparison.
By implementing compare( ), you can alter the way that objects are ordered. For
example, to sort in reverse order, you can create a comparator that reverses the
outcome of a comparison.
Overriding equals( ) is not necessary, and most simple comparators will not do so.
28
EXAMPLE
class Student { class AgeComparator implements
int rollno; Comparator {
public int Compare(Object o1,Object o2)
String name; {
int age; Student s1=(Student)o1;
Student s2=(Student)o2;
Student(int rollno,String name,
int age){
if([Link]==[Link])
[Link]=rollno; return 0;
[Link]=name; else if([Link]>[Link])
[Link]=age; return 1;
else
} return -1;
} }
}
29
class NameComparator class Simple{
implements Comparator{ public static void main(String args[]){
public int Compare(Object o1, ArrayList al=new ArrayList();
Object o2){ [Link](new Student(101,“vde",23));
[Link](new Student(106,“ali",27));
Student s1=(Student)o1; [Link](new Student(105,“hes",21));
Student s2=(Student)o2; [Link]("Sorting by Name...");
[Link](al,new NameComparator());
for (Student st : al)
return [Link] [Link]([Link]+" "+[Link]+" "+st
([Link]); .age);
} [Link]("sorting by age...");
} [Link](al,new AgeComparator());
for (Student st : al)
[Link]([Link]+" "+[Link]+" "+st
.age);
}
30
COMPARABLE EXAMPLE
class Student implements Comparable{
int rollno; String name; int age; ….
public int compareTo (Object obj){
Student st=(Student)obj;
if(age==[Link])
return 0;
else if(age>[Link])
return 1;
else return -1; } }
31