Lecture 7 Generic Class, STL and Collection Framework
Lecture 7 Generic Class, STL and Collection Framework
➢ Generic class, interface or method uses type parameter It is recommended that type parameter names
be single character capital letter like T, V and E.
➢ Java does not allow a primitive type as a type parameter. However, it’s not a serious problem due
having wrappers to encapsulate each primitive type. Java’s autoboxing and auto-unboxing makes the
use of wrapper transparent.
➢ When code with generic class, interface or method is compiled, all generic type information is removed
and type parameter is replaced with compatible type. This is known as Erasure.
➢ A generic class cannot extend Throwable. This means that you cannot create generic exception classes.
2
Generic Class
#include <iostream> int main(){
using namespace std; Gen<int> iob(88);
iob.showType();
C++ Code
template <typename T>
class Gen{
cout << "Value: " << iob.getob() << endl;
T ob;
public: Gen<double> dob(22.22);
Gen(T o){ ob = o;} dob.showType();
T getob(){ return ob;} cout << "Value: " << dob.getob() << endl;
void showType();
}; Gen<char *> cob("Template Test");
template <class T>
cob.showType();
void Gen<T>::showType(){ cout << "Value: " << cob.getob() << endl;
cout << "Type: " <<typeid(ob).name()<<endl;
} // iob = cob; // Error: incompatible types
OUTPUT:
Type of T is: i return 0;
Value: 88 }
Type of T is: d
template <typename T>
Value: 22.22
Type of T is: Pc can also be used instead of
Value: Template Test template <class T> and Vice-Versa
3
Generic Class
class Gen <T>{
T ob;
Gen(T o){ ob = o; }
T getOb(){ return ob;}
void showType(){
System.out.println("Type of T: "+ob.getClass().getName());
}
}
OUTPUT:
Java Code
C++ Code
template <class T, class V>
Java Code
V getOb2(){ return ob2; }
class Gen{
void showType(){
T ob1; V ob2;
System.out.println("Type of T: "+ob1.getClass().getName());
public:
System.out.println("Type of V: "+ob2.getClass().getName());
Gen(T o1, V o2){ ob1 = o1; ob2 = o2;}
}
T getob1(){ return ob1;}
}
V getob2(){ return ob2;}
public class Main {
void showType(){
public static void main(String[] args) {
cout << "Type of T is: " << typeid(ob1).name() << endl;
Gen<Integer, String> ob = new Gen<>(88, "Double Type
cout << "Type of V is: " << typeid(ob2).name() << endl;
Parameters");
}
ob.showType();
};
System.out.println("Value: "+ob.getOb1());
System.out.println("Value: "+ob.getOb2());
int main(){
}
Gen<int, char *> iob(88, "Double Type Parameters");
}
iob.showType();
cout << "Value: " << iob.getob1() << endl;
cout << "Value: " << iob.getob2() << endl;
OUTPUT:
Type of T is: i
return 0; Type of V is: Pc
} Value: 88
Value: Double Type Parameters 7
Bounded Type Parameters in Java
class Stats<T extends Number>{
T[] nums;
Stats(T[] o){ nums = o; }
How can a method average() double average(){
double sum = 0.0;
be added in a generic class? for( T num: nums )
sum += num.doubleValue();
return sum / nums.length;
}
}
Bounded Type Parameters public class Main {
public static void main(String[] args) {
Integer[] inums={1, 2, 3, 4, 5};
Stats<Integer> iOb = new Stats<>(inums);
System.out.println("Integer Avg: " + iOb.average());
C++ Code
void swapargs(T &a, T &b){
T temp = a; swapargs(i, j);
a = b; cout << i << " " << j << endl;
b = temp;
} swapargs(x, y);
cout << x << " " << y << endl;
void swapargs(int &a, int &b){
int temp = a; swapargs(a, b);
a = b; cout << a << " " << b << endl;
b = temp;
cout << "Non-Generic swap" << endl; Gen g;
} g.showType(i); OUTPUT:
g.showType(x); Non-Generic swap
class Gen{ //non-generic class g.showType(a); 20 10
public: 23.3 10.1
template <typename T> return 0;
}
y x
void showType(T &a){
Type: i
cout << "Type: " << typeid(a).name() << endl;
} Type: f
}; Type: c
12
Generic Method in Java
public class Main { ❖ The Type Parameters is declared before
static <T extends Comparable<T>, V extends T>
boolean isIn(T x, V[] list){
the return type of a method.
for(T y: list) ❖ Comparable is a Generic Interface
if (x.equals(y)) return true;
return false; defined in java.lang and its Type
} Parameter specifies the type of objects
that that it compares.
public static void main(String[] args) {
Integer[] nums = {2, 4, 6, 7, 8, 3, 5};
String[] strs ={"One", "Two", "Three"};
if (isIn(2, nums))
System.out.println("2 is in nums");
if (isIn("Two", strs))
System.out.println("Two is in strs");
}
} OUTPUT:
2 is in nums
Two is in strs 13
Generic Constructor
#include <iostream> class GenCons{
using namespace std; private double val;
Java Code
class GenCons{ <T extends Number>
C++ Code
double val; GenCons(T arg){
public: val = arg.doubleValue();
template <typename T> }
GenCons(T arg){ public void showVal(){
val = arg; System.out.println("Val: "+val);
} }
void showVal(){ }
cout << "Val: " << val << endl; public class Main {
} public static void main(String[] args) {
}; GenCons iVal = new GenCons(100);
GenCons dVal = new GenCons(25.6);
int main(){ iVal.showVal();
GenCons iVal(100); dVal.showVal();
GenCons dVal(25.6); }
}
iVal.showVal(); OUTPUT:
dVal.showVal(); Val: 100
} Val: 25.6 14
Generic Interface
interface MinMax<T extends Comparable<T>>{
T min(); public class Main {
T max(); public static void main(String[] args) {
} Integer[] iVals = {2, 4, 3, 1, 7, 9, 6};
String[] sVals = {"One", "Two", "Three", "Four"};
class MyClass <T extends Comparable<T>>
implements MinMax<T>{ MyClass<Integer> iOb = new MyClass<>(iVals);
T[] list; MyClass<String> sOb = new MyClass<>(sVals);
C++ Code
} };
};
int main(){
template <class T> NonGen ob(10);
class Gen : public NonGen{ Gen<char> ob1(20, 'A’);
T ob; Gen2D<double, char *> ob2(40, 60.5, "Gen2 Object");
public:
ob.show();
Gen(int n, T o) : NonGen(n){ ob = o; }
ob1.show();
OUTPUT:
T getob(){ return ob; } NonGen: 10
void show(){ ob2.show();
Gen: A
cout << "Gen: " << ob << endl;
} cout << ob1.getob() << endl; Gen2D: Gen2 Object
}; cout << ob2.getob() << endl; A
return 0; Gen2 Object
}
16
Generic in Inheritance
class NonGen{
public class Main {
private int num;
public static void main(String[] args) {
NonGen(int n) { num = n;}
NonGen ob = new NonGen(10);
public void show(){
Gen<Character> ob1 = new Gen<>(20, 'A');
System.out.println("NonGen: "+num);
Gen2<Double, String> ob2 = new Gen2<>(40, 60.5, "Gen2 Object");
}
}
ob.show();
ob1.show();
class Gen<T> extends NonGen{
ob2.show();
private T ob;
Gen(int n, T o){ super(n); ob = o; }
System.out.println(ob1.getOb());
public T getOb(){ return ob; }
System.out.println(ob2.getOb2());
public void show(){
}
System.out.println("Gen: "+ob);
}
}
}
OUTPUT:
class Gen2<T, V> extends Gen<T>{ NonGen: 10
private V ob;
Gen: A
Gen2(int n, T o1, V o2){ super(n, o1); ob = o2; }
public V getOb2(){ return ob; } Gen2D: Gen2 Object
public void show(){ A
System.out.println("Gen2: "+ob); Gen2 Object
}
}
17
Standard Template Library(STL)
C++
18
STL Items
At the core of Standard Template Library (STL) are three fundamental Items:
Containers, Algorithms and Iterators.
❖ Containers: containers are objects that hold other objects.
❖ Algorithms: algorithms act containers. Their capabilities includes initialization, sorting,
searching and transforming the contents of containers.
❖ Iterators: iterators are objects that act like pointer to the contents of a container with the
ability to cycle.
➢ Besides these three Items, STL relies upon some standard components like allocators, predicates,
comparison functions and function objects.
➢ In addition to the headers required by the various STL classes, the C++ standard library includes the
<utility> and <functional> headers, which provide support for the STL.
19
Containers
Containers
bidirectional None
Some examples of Containers
20
Some functions associated with Containers
Some commonly used functions:
Function Purpose Containers Applicable
insert() Insert an elements Sequence containers, Associative containers
erase() Remove elements Sequence containers, Associative containers
push_back() Add an element at the end. Sequence containers
pop_back() Remove an element from the end Sequence containers
push_front() Add an element at the start. list and deque containers
pop_front Remove an element from the start list and deque containers
size() Return the current size of the container Sequence containers, Associative containers
sort() Sort data within the range in custom order Array, vector, deque, etc.
merge() Combine two sorted ranges.
empty()
clear()
make_pair()
21
typedef defined in STL
Some of the most common typedef names defined in STL:
Containers Applicable
size_type Some type of integer
Reference A reference to an element ➢ Overloaded operators <, <=,
>, >=, == and != perform
const_reference A const reference to an element
element-by-element
iterator An iterator comparisons.
const_iterator A const iterator
reverse_iterator A reverse iterator ➢ Overloaded operators <, <=,
const_reverse_iterator A const reverse iterator > and >= are not provided
for the unordered
value_type The type of a value stored in a container
associative containers.
allocator_type The type of the allocator
key_type The type of a key
key_compare The type of a function that compares two keys
value_compare The type of a function that compares two values
22
Iterators
➢ Iterators are objects that like pointers. Random Access
There are five types of iterators:
Iterator Actions Direction Bidirectional
Random Access Store and Retrieve values Elements may be accessed randomly.
Bidirectional Store and Retrieve values Forward and Backward moving Forward
Forward Store and Retrieve values Forward moving only.
Input Retrieve, but not Store Forward moving only.
Output Store, but not Retrieve Forward moving only. Input Output
27
Algorithms
Algorithms act on containers. Header <algorithm> should be included.
Some Algorithms:
Name Format Explanation
count() int n = count(v.begin(), v.end(), val) Returns the number of elements in the sequence beginning
at v.begin() and ending at v.end() that match val
count_if() int n = count_if(v.begin(), v.end(), Returns the number of elements in the sequence beginning
even) at v.begin() and ending at v.end() for which the unary
predicate even returns true
remove_copy() remove_copy(v.begin(), v.end(), Copies elements from the specified range, i.e., from v.begin()
back_inserter(v2), val) to v.end() that are not equal to val and puts the results into
the sequence pointed by v2.begin()
reverse() reverse(v.begin(), v.end()) Reverse the order of the range specified
transform() transform(v.begin(), v.end(), Modifies each element in the range specified according to the
v.begin(), xform) function xform
28
Example Program using Algorithms
#include <iostream> for(int i = 1; i < 6; i++){
#include <list> myList.push_back(i * 3);
#include <algorithm> myList.push_front(i * 4);
using namespace std; }
29
Example Program using Algorithms
for(q = v2.begin(); q != v2.end(); q++){
cout << *q << " ";
}
cout << endl;
OUTPUT:
reverse(v2.begin(), v2.end()); 20 16 12 8 4 3 6 9 12 15
for(q = v2.begin(); q != v2.end(); q++){ 12 appears 2 times
cout << *q << " "; 7 even numbers.
} 20 16 8 4 3 6 9 15
15 9 6 3 4 8 16 20
cout << endl;
225 81 36 9 16 64 256 400
return 0;
}
30
Collection Framework
Java
31
Collection Framework
➢ The Collections Framework is a sophisticated hierarchy of interfaces and classes that provide
state-of-the-art technology for managing groups of objects. Package: java.util
➢ Three items of Collection Framework: Collections (Interfaces & Classes), Iterators and
Algorithms.
➢ Goals of Collection Framework:
✓ High efficiency and high performance
✓ Different types of collections to work in a similar manner and with a high degree of interoperability
➢ Legacy of ad-hoc classes before Collections: Dictionary, Vector, Stack and Properties.
➢ In addition to Collection interfaces, Collections also use Comparator, RandomAccess, Iterator,
ListIterator and Spliterator.
32
Collections
Interfaces Classes AbstractCollection
Extending Hierarchy
Iterable
Extending hierarchy
Collection
LinkedList LinkedHashSet
Deque SortedSet
Implementation:
NavigableSet ✓ AbstractCollection, AbstractList, AbstractQueue and AbstractSet
implement Collection, List, Queue and Set, respectively.
✓ ArrayDeque implemts Deque. 33
The Collection Interfaces
➢ Two Types of methods for interfaces: modifiable and unmodifiable. All the built-in Collections are
modifiable, i.e., allow to modify the contents of the collection.
Some Methods of Collection Interface:
Method Return Type Description
add() boolean add() adds a compatible object into the collection.
addAll() addAll() method adds the entire contents of a collection to another.
remove() boolean remove() removes an object from the collection.
removeAll(c) removeAll() removes all objects of c from the collection.
removeIf() removeIf() removes objects that satisfy the condition specified by predicate.
retainAll(c) retainAll() removes all objects from the invoking collection except those in c.
clear() void Clear or remove all objects.
contains() boolean contains() checks whether a collection contains a specific object.
containAll() containAll() checks whether one collection contains all the members of another.
isEmpty() boolean Returns true if the invoking collection is empty.
size() int Returns the number of elements in the invoking collection.
toString() Object[] Returns an array of elements from the invoking collection.
34
The Collection Interface
Some Methods of Collection Interface:
Method Return Type Description
equals() boolean Returns true if the invoking collection and object are equal.
iterator() Iterator Returns an Iterator for the invoking collection.
spliterator() Spliterator Returns a Spliterator from the invoking collection.
stream() Stream Returns a stream that uses the invoking collection as its source of elements.
parallelStream() Returned stream supports parallel operations, if possible.
36
The Queue Interface
37
Iterator
Iterator: A standardized way of accessing the elements within a collection, one at a time. It’s an
Interface.
ListIterator: It extends Iterator interface and used for all types of list including ArrayList, Vector,
LinkedList, Stack, etc. Access the collection either forward or backward directions.
Spliterator: Provide support for parallel iteration.
PrimitiveIterator: Used for primitive data type. For example, PrimitiveIterator.OfDouble
Class iterator
implements Iterator
Interface.
38
Iterator
Methods used in Iterator:
Method Return Type Description
hasNext() boolean Returns true if the iterator has more elements.
next() Object Returns the next element of the iterator. Throws
NoSuchElementException if no more element is present.
remove() void Removes the current element in the collection. If it is not followed by
next() method, then throws IllegalStateException.
Interfaces Classes
AbstractMap
Map Map.Entry
Nested interface
of Map
EnumMap HashMap TreeMap WeakHashMap
SortedMap
IdentityHashMap
AbstractSequentialList
NavigableMap
41
Map
Some Methods of Map Interface:
Method Return Type Description
get() Value To obtain a value passing the key as an argument.
put() Value To put a value into a Map specifying the key and value. Returns the
previous value linked to the key is returned. Returns null if the key did not
already exist.
entrySet() Set Returns a Set that contains the entries in the map. The set contains objects
of type Map.Entry.
getKey() Key To obtain the collection-view of keys.
getValue() Value To obtain the collection-view of values.
containsKey() boolean Returns true if the invoking map contains k as a key. Otherwise, returns
false.
containsValue() boolean Returns true if the map contains v as a value. Otherwise, returns false.
42
Map
import java.util.HashMap;
import java.util.Map;
import java.util.Set;
44
Comparator
import java.util.Comparator; import java.util.Comparator;
import java.util.TreeSet; import java.util.TreeSet;