Java Collections and Generics
Java Collections and Generics
Java Collections and Generics
and
Generics
java.util package
By Waqas 1
Java Collection Framework
By Waqas 2
Java Collection Framework
Interfaces
By Waqas 5
Implementations
Algorithms
By Waqas 7
Collection Map
SortedSet
Collection Framework
Interfaces
By Waqas 8
Collection Interface
A Collection interface is the super interface in the
collection interfaces hierarchy. A collection
represents a group of objects, known as its elements.
By Waqas 9
Set Interface
A Set is a Collection that does not contain duplicate
elements, so its a collection of unique elements. If
you add duplicate element in Set then add( ) method
simply ignore the element and return false.
By Waqas 11
SortedSet Interface
The SortedSet interface extends Set and declares the
behavior of a set in which objects are sorted in either
their natural order or the order you specified in your
custom object.
By Waqas 12
Map Interface
By Waqas 14
Difference between Interfaces
Interface Duplicates Order Sorting
By Waqas 15
Collection Framework
Implementations
By Waqas 16
Set SortedSet List
Vector
Map SortedMap
Collection Framework
HashMap TreeMap
Implementations
By Waqas 17
ArrayList Class
ArrayList class implements the List interface.
By Waqas 22
TreeMap Class
By Waqas 23
Comparable Interface
Many java collection framework classes such as
TreeMap, TreeSet perform automatic sorting of
objects when they added in the collection.
return st1.compareTo(st2);
By Waqas 25
Arrays Class
Arrays class contains various methods for
manipulating arrays.
By Waqas 28
Comparator Interface
Arrays.sort(students,
By Waqasnew 29
Collections Class
Collections class contains various methods for
manipulating collections.
sort( List );
binarySearch( List, Object );
min(List);
max(List);
replaceAll(List, Object, Object);
reverse(List);
shuffle(List);
swap(List, int, int);
By Waqas 30
Java Generics
By Waqas 31
Example of Generic Errors
When we retrieve an element from a collection, we
need to cast it to the right type otherwise compile
time error occur.
By Waqas 32
Example of Generic Errors
There is no way to ensure that we are casting to a
correct type. Following code will compile but it will
throw exception at runtime.
By Waqas 33
Java Generics
Generics in Java allow us to create collections with
a strong type.
By Waqas 34
Generic ArrayList
ArrayList<E> list = new ArrayList<E>();
list.add(Simon);
list.add(Peter);
String s1 = list.get(0);
String s2 = list.get(1);
By Waqas 35
Generic TreeSet
TreeSet<E> set = new TreeSet<E>();
; set.add(new Integer(2))
set.add(new Integer(3));
By Waqas 36
Generic TreeMap
TreeMap<K,V> map = new TreeMap<K,V>();
By Waqas 37
Generic Iterator
Iterator<E> it = set.iterator();
Iterator<String> it = set.iterator();
String s;
while(it.hasNext())
{
s = it.next();
}
By Waqas 38