Object Oriented Programming
Dr. Tanmaya Mahapatra
BITS Pilani Department of Computer Science and Information Systems
Pilani Campus
Contents
• Introduction to Collection Framework
• Collection Interfaces and their methods
• Collection Classes
• Basic Demos
CS F213 Object Oriented Programming 2
BITS Pilani, Pilani Campus
The Collection Framework
• The Collection in Java is a framework that provides an
architecture to store and manipulate the group of objects.
• Java Collections support data operations → searching, sorting,
insertion, manipulation and deletion.
• Java Collection → a single unit of objects.
• Java Collection framework provides many interfaces
– Set List, Queue, Deque
• classes
– ArrayList, Vector, LinkedList, PriorityQueue, HashSet, LinkedHashSet,
TreeSet
CS F213 Object Oriented Programming 3
BITS Pilani, Pilani Campus
Framework
• It provides readymade architecture consisting of a set of
classes and interfaces.
• It is optional.
• The Collection framework represents a unified architecture
for storing and manipulating a group of objects.
• It has:
1. Interfaces and its implementations, i.e., classes
2. Algorithm
Source:
[Link]
CS F213 Object Oriented Programming 4
BITS Pilani, Pilani Campus
The Collection Framework
• The Java Collections Framework standardizes the way in which
groups of objects are handled by Java programs.
• Java provided ad hoc classes such as Dictionary, Vector,
Stack, and Properties to store and manipulate groups of
objects.
• Although these classes were quite useful, they lacked a
central, unifying theme.
• The way that we used Vector was different from the way that
we used Properties.
CS F213 Object Oriented Programming 5
BITS Pilani, Pilani Campus
The Collection Framework
• The Collections Framework was designed to meet several goals.
1. The framework had to be high-performance. The implementations
for the fundamental collections (dynamic arrays, linked lists, trees,
and hash tables) are highly efficient. Very rarely these “data
engines” are coded manually in Java.
2. The framework had to allow different types of collections to work
in a similar manner and with a high degree of interoperability.
3. Extending and/or adapting a collection had to be easy. 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 which can be used as-
is.
• We can also implement our own collection, if required.
CS F213 Object Oriented Programming 6
BITS Pilani, Pilani Campus
The Collection Framework
• Algorithms are another important part of the collection mechanism.
• Algorithms operate on collections and are defined as static methods within the
Collections class. They are available for all collections. Each collection class need
not implement its own versions. The algorithms provide a standard means of
manipulating collections.
• Collections Framework & the Iterator interface.
• An iterator offers a general-purpose, standardized way of accessing the elements
within a collection, one at a time.
• An iterator provides a means of enumerating the contents of a collection.
• Because each collection provides an iterator, the elements of any collection class
can be accessed through the methods defined by Iterator.
• With only small changes, the code that cycles through a set can also be used to
cycle through a list, for example.
CS F213 Object Oriented Programming 7
BITS Pilani, Pilani Campus
Collection Interface
• The Collection interface is the foundation upon which the
Collections Framework is built because it must be
implemented by any class that defines a collection.
• Collection is a generic interface that has this declaration:
– interface Collection<E>
• E specifies the type of objects that the collection will hold.
• Collection extends the Iterable interface. This means that all
collections can be cycled through by use of the for-each style
for loop.
• Collection declares the core methods that all collections will
have.
CS F213 Object Oriented Programming 8
BITS Pilani, Pilani Campus
Collection Interface
• Objects are added to a collection by calling add( ).
• add( ) takes an argument of type E, which means that objects
added to a collection must be compatible with the type of
data expected by the collection.
• Add the entire contents of one collection to another by calling
addAll( ).
• Remove an object by using remove( ).
• Remove a group of objects by using removeAll( ).
• Remove all elements except those of a specified group by
calling retainAll( ).
CS F213 Object Oriented Programming 9
BITS Pilani, Pilani Campus
Collection Interface
• Remove an element only if it satisfies some condition →
removeIf( ).
• To empty a collection → clear( ).
• We can determine whether a collection contains a specific
object by calling contains( ).
• To determine whether one collection contains all the
members of another → containsAll( ).
• Determine when a collection is empty → isEmpty( ).
• The number of elements currently held in a collection can be
determined by calling size( ).
• The toArray( ) methods return an array that contains the
elements stored in the collection.
CS F213 Object Oriented Programming 10
BITS Pilani, Pilani Campus
Collection Interface
• Two collections can be compared for equality by calling
equals( ).
• The precise meaning of “equality” may differ from collection
to collection.
• For example, you can implement equals( ) so that it compares
the values of elements stored in the collection.
• equals( ) can also compare references to those elements.
• The most important method is iterator( ), which returns an
iterator to a collection.
CS F213 Object Oriented Programming 11
BITS Pilani, Pilani Campus
Collection Interface: Methods
CS F213 Object Oriented Programming 12
BITS Pilani, Pilani Campus
Collection Interface: Methods
CS F213 Object Oriented Programming 13
BITS Pilani, Pilani Campus
The List Interface
• The List interface extends Collection and declares the
behavior of a collection that stores a sequence of elements.
• Elements can be inserted or accessed by their position in the
list, using a zero-based index.
• A list may contain duplicate elements.
• List is a generic interface that has this declaration:
• interface List<E>
• E specifies the type of objects that the list will hold.
• In addition to the methods defined by Collection, List defines
some of its own.
CS F213 Object Oriented Programming 14
BITS Pilani, Pilani Campus
The List Interface
1. To the versions of add( ) and addAll( ) defined by Collection, List adds the methods
add(int, E) and addAll(int, Collection).
1. These methods insert elements at the specified index.
2. The semantics of add(E) and addAll(Collection) defined by Collection are changed
by List so that they add elements to the end of the list.
3. Modify each element in the collection by using replaceAll( ).
4. To obtain the object stored at a specific location → get( ) with the index of the
object.
5. To assign a value to an element in the list → set( ), specifying the index of the
object to be changed.
6. To find the index of an object → indexOf() or lastIndexOf( ).
7. Obtain a sublist of a list by calling subList( ), specifying the beginning and ending
indexes of the sublist.
8. One way to sort a list is with the sort( ) method defined by List.
CS F213 Object Oriented Programming 15
BITS Pilani, Pilani Campus
The Set Interface
• The Set interface defines a set.
• It extends Collection and specifies the behavior of a collection that does
not allow duplicate elements.
• The add( ) method returns false if an attempt is made to add duplicate
elements to a set.
• Set is a generic interface that has this declaration:
– interface Set<E>
• E specifies the type of objects that the set will hold.
CS F213 Object Oriented Programming 16
BITS Pilani, Pilani Campus
The SortedSet Interface
• The SortedSet interface extends Set and declares the behavior of a set sorted in
ascending order.
• SortedSet is a generic interface that has this declaration:
– interface SortedSet<E>
• E specifies the type of objects that the set will hold.
• SortedSet defines several methods that make set processing more convenient.
• To obtain the first object in the set → first( ).
• To get the last element → last( ).
• We can obtain a subset of a sorted set by calling subSet(), specifying the first and
last object in the set.
• If we need the subset that starts with the first element in the set → headSet( ).
• If we need the subset that ends the set → tailSet( ).
CS F213 Object Oriented Programming 17
BITS Pilani, Pilani Campus
The NavigableSet Interface
• The NavigableSet interface extends SortedSet and declares
the behavior of a collection that supports the retrieval of
elements based on the closest match to a given value or
values.
• NavigableSet is a generic interface that has this declaration:
– interface NavigableSet<E>
• E specifies the type of objects that the set will hold.
CS F213 Object Oriented Programming 18
BITS Pilani, Pilani Campus
Queue Interface
• The Queue interface extends Collection and declares the behavior of a
queue, which is often a first-in, first-out list.
• There are types of queues in which the ordering is based upon other
criteria.
• Queue is a generic interface that has this declaration:
– interface Queue<E>
• E specifies the type of objects that the queue will hold.
CS F213 Object Oriented Programming 19
BITS Pilani, Pilani Campus
Queue Interface
• Elements can only be removed from the head of the queue.
• There are two methods that obtain and remove elements:
poll( ) and remove( ).
• The difference between them is that poll( ) returns null if the
queue is empty, but remove( ) throws an exception.
• There are two methods, element( ) and peek( ), that obtain
but don’t remove the element at the head of the queue.
• They differ only in that element( ) throws an exception if the
queue is empty, but peek( ) returns null.
• offer( ) only attempts to add an element to a queue. Because
some queues have a fixed length and might be full, offer( )
can fail.
CS F213 Object Oriented Programming 20
BITS Pilani, Pilani Campus
Queue Interface
CS F213 Object Oriented Programming 21
BITS Pilani, Pilani Campus
Dequeue Interface
• The Deque interface extends Queue and declares the
behavior of a double-ended queue.
• Double-ended queues can function as standard, first-in, first-
out queues or as last-in, first-out stacks.
• Deque is a generic interface that has this declaration:
– interface Deque<E>
• E specifies the type of objects that the deque will hold
CS F213 Object Oriented Programming 22
BITS Pilani, Pilani Campus
Dequeue Interface
• Deque includes the methods push( ) and pop( ) →enable a Deque to function as a
stack.
• descendingIterator( )→ returns an iterator that returns elements in reverse order.
it returns an iterator that moves from the end of the collection to the start.
• A Deque implementation can be capacity-restricted, which means that only a
limited number of elements can be added to the deque.
• When this is the case, an attempt to add an element to the deque can fail.
• Deque handles such failures in two ways:
1. addFirst( ) and addLast( ) throw an IllegalStateException if a capacity-restricted
deque is full.
2. offerFirst( ) and offerLast( ) return false if the element cannot be added.
CS F213 Object Oriented Programming 23
BITS Pilani, Pilani Campus
Collection Classes
• Collection Classes → standard classes that implement the
Collection Interfaces.
• Some of the classes provide full implementations that can be
used as-is.
• Others are abstract, providing skeletal implementations that
are used as starting points for creating concrete collections.
CS F213 Object Oriented Programming 24
BITS Pilani, Pilani Campus
The Collection Framework
Source:
[Link]
CS F213 Object Oriented Programming 25
BITS Pilani, Pilani Campus
Collection Classes
CS F213 Object Oriented Programming 26
BITS Pilani, Pilani Campus
Basic Examples
• Demo
CS F213 Object Oriented Programming 27
BITS Pilani, Pilani Campus
What has been covered?
• Introduction to Collection Framework ✔
• Collection Interfaces and their methods ✔
• Collection Classes ✔
• Basic Examples (Demo) ✔
CS F213 Object Oriented Programming 28
BITS Pilani, Pilani Campus
Object Oriented Programming
Dr. Tanmaya Mahapatra
BITS Pilani Department of Computer Science and Information Systems
Pilani Campus
Contents
• Collection Classes : ArrayList
• LinkedList
• HashSet & LinkedHashSet
• TreeSet & ArrayDeque
• Iterator & ListInterator
• For-Each Alternative
• Storing Objects of Custom Classes in Collections
CS F213 Object Oriented Programming 2
BITS Pilani, Pilani Campus
CS F213 Object Oriented Programming 3
BITS Pilani, Pilani Campus
CS F213 Object Oriented Programming 4
BITS Pilani, Pilani Campus
The ArrayList Class
• The ArrayList class extends AbstractList and implements the List interface.
• ArrayList is a generic class:
– class ArrayList<E>
• E specifies the type of objects that the list will hold.
• ArrayList supports dynamic arrays that can grow as needed.
• In Java, standard arrays are of a fixed length. After arrays are created, they
cannot grow or shrink.
• We may not know until run time precisely how large an array we need.
• To handle this situation, the Collections Framework defines ArrayList.
• An ArrayList is a variable-length array of object references.
• An ArrayList can dynamically increase or decrease in size. Array lists are
created with an initial size. When this size is exceeded, the collection is
automatically enlarged. When objects are removed, the array can be
shrunk.
CS F213 Object Oriented Programming 5
BITS Pilani, Pilani Campus
The ArrayList Class
• ArrayList has the constructors:
1. ArrayList( )
2. ArrayList(Collection<? extends E> c)
3. ArrayList(int capacity)
• The syntax ? extends E means “some type that either is E or a subtype of E”.
The ? is a wildcard.
• The first constructor builds an empty array list.
• The second constructor builds an array list that is initialized with the elements
of the collection c.
• The third constructor builds an array list 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 array list.
• Demo → ArrayListDemo
CS F213 Object Oriented Programming 6
BITS Pilani, Pilani Campus
The ArrayList Class
• Although the capacity of an ArrayList object increases automatically as
objects are stored in it, we can increase the capacity of an ArrayList object
manually by calling ensureCapacity( ).
• We might want to do to prevent several reallocations later. Because
reallocations are costly in terms of time, preventing unnecessary ones
improves performance. The signature for ensureCapacity( ) is:
• void ensureCapacity(int cap)
• cap specifies the new minimum capacity of the collection.
• If we want to reduce the size of the array that underlies an ArrayList
object so that it is precisely as large as the number of items that it is
currently holding → trimToSize()
• void trimToSize( )
CS F213 Object Oriented Programming 7
BITS Pilani, Pilani Campus
Obtaining Array from ArrayList
• When working with ArrayList, we can obtain an actual array that contains
the contents of the list. → toArray(), which is defined by Collection.
1. To obtain faster processing times for certain operations
2. To pass an array to a method that is not overloaded to accept a collection
3. To integrate collection-based code with legacy code that does not
understand collections
• There are three versions of toArray( ):
1. object[ ] toArray( )
2. <T> T[ ] toArray(T array[ ])
3. default <T> T[ ] toArray(IntFunction<T[ ]> arrayGen)
• The first returns an array of Object.
• The second and third forms return an array of elements that have the
same type as T. Demo → ArrayListToArrayDemo
CS F213 Object Oriented Programming 8
BITS Pilani, Pilani Campus
LinkedList Class
• The LinkedList class extends AbstractSequentialList and implements the
List, Deque, and Queue interfaces.
• It provides a linked-list data structure.
• LinkedList is a generic class:
– class LinkedList<E>
• E specifies the type of objects that the list will hold.
• LinkedList has two constructors:
• LinkedList( )
• LinkedList(Collection<? extends E> c)
• The first constructor builds an empty linked list.
• The second constructor builds a linked list that is initialized with the
elements of the collection c.
CS F213 Object Oriented Programming 9
BITS Pilani, Pilani Campus
LinkedList Class
• Because LinkedList implements the Deque interface, we have access to
the methods defined by Deque.
• For example, to add elements to the start of a list → use addFirst( ) or
offerFirst( ).
• To add elements to the end of the list → addLast( ) or offerLast( ).
• To obtain the first element → getFirst( ) or peekFirst( ).
• To obtain the last element → getLast( ) or peekLast( ).
• To remove the first element → removeFirst( ) or pollFirst( ).
• To remove the last element → removeLast( ) or pollLast( ).
• Demo → LinkedListDemo
• Because LinkedList implements the List interface, calls to add(E) append
items to the end of the list, as do calls to addLast( ).
• To insert items at a specific location → add(int, E) form of add( ).
CS F213 Object Oriented Programming 10
BITS Pilani, Pilani Campus
The HashSet Class
• HashSet extends AbstractSet and implements the Set interface.
• It creates a collection that uses a hash table for storage.
• HashSet is a generic class that has the declaration:
– class HashSet<E>
• E specifies the type of objects that the set will hold.
• A hash table stores information by using a mechanism called hashing.
• In hashing, the informational content of a key is used to determine a
unique value, called its hash code.
• The hash code is then used as the index at which the data associated with
the key is stored. The transformation of the key into its hash code is
performed automatically. The code can’t directly index the hash table.
• The advantage of hashing is that it allows the execution time of add( ),
contains( ), remove( ), and size( ) to remain constant even for large sets.
CS F213 Object Oriented Programming 11
BITS Pilani, Pilani Campus
The HashSet Class
• HashSet( )
• HashSet(Collection<? extends E> c)
• HashSet(int capacity)
• HashSet(int capacity, float fillRatio)
• The first form constructs a default hash set.
• The second form initializes the hash set by using the elements of c.
• The third form initializes the capacity of the hash set to capacity. (The
default capacity is 16.)
• The fourth form initializes both the capacity and the fill ratio (also called
load factor) of the hash set from its arguments. The fill ratio must be
between 0.0 and 1.0, and it determines how full the hash set can be
before it is resized upward.
• Demo → HashSet
CS F213 Object Oriented Programming 12
BITS Pilani, Pilani Campus
The HashSet Class
• HashSet stores the elements by using a mechanism
called hashing.
• HashSet contains unique elements only.
• HashSet allows null value.
• HashSet doesn't maintain the insertion order. Elements are
inserted on the basis of their hashcode.
• HashSet is the best approach for search operations.
• The initial default capacity of HashSet is 16, and the load
factor is 0.75.
CS F213 Object Oriented Programming 13
BITS Pilani, Pilani Campus
The LinkedHashSet Class
• The LinkedHashSet class extends HashSet and adds no members of its own.
• It is a generic class:
• class LinkedHashSet<E>
• E specifies the type of objects that the set will hold.
• LinkedHashSet maintains a linked list of the entries in the set, in the order in which
they were inserted.
• This allows insertion-order iteration over the set.
• When cycling through a LinkedHashSet using an iterator, the elements will be
returned in the order in which they were inserted.
• This is also the order in which they are contained in the string returned by
toString( ) when called on a LinkedHashSet object.
• Demo → LinkedHashSet
CS F213 Object Oriented Programming 14
BITS Pilani, Pilani Campus
The TreeSet Class
• TreeSet extends AbstractSet and implements the NavigableSet interface.
1. It creates a collection that uses a tree for storage.
2. Objects are stored in sorted, ascending order.
3. Access and retrieval times are quite fast, which makes TreeSet an excellent choice
when storing large amounts of sorted information that must be found quickly.
• TreeSet is a generic class:
• class TreeSet<E>
• E specifies the type of objects that the set will hold.
CS F213 Object Oriented Programming 15
BITS Pilani, Pilani Campus
The TreeSet Class
• TreeSet has the following constructors:
• TreeSet( )
• TreeSet(Collection<? extends E> c)
• TreeSet(Comparator<? super E> comp)
• TreeSet(SortedSet<E> ss)
• The first form constructs an empty tree set that will be sorted in ascending order
according to the natural order of its elements.
• The second form builds a tree set that contains the elements of c.
• The third form constructs an empty tree set that will be sorted according to the
comparator specified by comp. (Later)
• The fourth form builds a tree set that contains the elements of ss.
• Demo → TreeSetDemo
CS F213 Object Oriented Programming 16
BITS Pilani, Pilani Campus
ArrayDeque Class
• The ArrayDeque class extends AbstractCollection and implements the Deque interface.
• It adds no methods of its own.
• ArrayDeque creates a dynamic array and has no capacity restrictions. (The Deque
interface supports implementations that restrict capacity, but does not require such
restrictions.)
• ArrayDeque is a generic class:
• class ArrayDeque<E>
• E specifies the type of objects stored in the collection.
• ArrayDeque defines the following constructors:
• ArrayDeque( )
• ArrayDeque(int size)
• ArrayDeque(Collection<? extends E> c)
• The first constructor builds an empty deque. Its starting capacity is 16.
• The second constructor builds a deque that has the specified initial capacity.
• The third constructor creates a deque that is initialized with the elements of the
collection passed in c. Demo → ArrayDeque
CS F213 Object Oriented Programming 17
BITS Pilani, Pilani Campus
Iterator
• We may want to cycle through the elements in a collection.
• For example → display each element.
• One way to do this is to employ an iterator, which is an object that implements
either the Iterator or the ListIterator interface.
• Iterator enables to cycle through a collection, obtaining or removing elements.
• ListIterator extends Iterator to allow bidirectional traversal of a list, and the
modification of elements.
• Iterator and ListIterator are generic interfaces:
• interface Iterator<E>
• interface ListIterator<E>
CS F213 Object Oriented Programming 18
BITS Pilani, Pilani Campus
Iterator
• Each of the collection classes provides an iterator( ) method that returns an
iterator to the start of the collection.
• By using this iterator object, we can access each element in the collection, one
element at a time.
1. Obtain an iterator to the start of the collection by calling the collection’s iterator( )
method.
2. Set up a loop that makes a call to hasNext( ). Have the loop iterate as long as
hasNext( ) returns true.
3. Within the loop, obtain each element by calling next( ).
• For collections that implement List, we can also obtain an iterator by calling
listIterator( ). A list iterator gives the ability to access the collection in either the
forward or backward direction and permits modification of an element.
• Demo →Iterator
CS F213 Object Oriented Programming 19
BITS Pilani, Pilani Campus
For-Each Alternative
• If modifying the contents of a collection or obtaining elements
in reverse order is not needed, then the for-each version of
the for loop is often a more convenient alternative to cycling
through a collection than is using an iterator.
• The for can cycle through any collection of objects that
implement the Iterable interface.
• Because all of the collection classes implement this interface,
they can all be operated upon by the for.
• Demo → ForEachDemo
CS F213 Object Oriented Programming 20
BITS Pilani, Pilani Campus
Storing User Defined Types in
Collections
• Collections are not limited to the storage of built-in objects
like Integer, String etc.
• They can store any type of object, including objects of classes
that we create.
• Demo → MailList
CS F213 Object Oriented Programming 21
BITS Pilani, Pilani Campus
What has been covered?
• Collection Classes : ArrayList ✔
• LinkedList ✔
• HashSet & LinkedHashSet ✔
• TreeSet & ArrayDeque ✔
• Iterators & ListInterator ✔
• For-Each Alternative ✔
• Storing Objects of Custom Classes in Collections ✔
CS F213 Object Oriented Programming 22
BITS Pilani, Pilani Campus
Object Oriented Programming
BITS Pilani Dr. Tanmaya Mahapatra
Pilani Campus Department of Computer Science and Information Systems
Contents
• UML Notations
CS F213 Object Oriented Programming 2
BITS Pilani, Pilani Campus
Class
• Class
• A class is represented by a rectangle with three sections −
1. the top section containing the name of the class
2. the middle section containing class attributes
3. the bottom section representing operations of the class
• The visibility of the attributes and operations are represented in the following
ways −
• Public − A public member is visible from anywhere in the system. In class diagram,
it is prefixed by the symbol ‘+’.
• Private − A private member is visible only from within the class. It cannot be
accessed from outside the class. A private member is prefixed by the symbol ‘−’.
• Protected − A protected member is visible from within the class and from the
subclasses inherited from this class, but not from outside. It is prefixed by the
symbol ‘#’.
• An abstract class has the class name written in italics.
CS F213 Object Oriented Programming 3
BITS Pilani, Pilani Campus
Class
Unified Modelling Language
(UML) representation of
the Television class for object-
oriented modelling and
programming.
CS F213 Object Oriented Programming 4
BITS Pilani, Pilani Campus
Class
• A class represent a concept which encapsulates state (attributes) and behavior
(operations).
• Each attribute has a type. Each operation has a signature.
• The class name is the only mandatory information.
• Class Name:
• The name of the class appears in the first partition.
• Class Attributes:
• Attributes are shown in the second partition.
• The attribute type is shown after the colon.
• Class Operations (Methods):
• Operations are shown in the third partition. They are services the class provides.
• The return type of a method is shown after the colon at the end of the method
signature.
• The return type of method parameters are shown after the colon following the
parameter name. Operations map onto class methods in code.
CS F213 Object Oriented Programming 5
BITS Pilani, Pilani Campus
CS F213 Object Oriented Programming 6
BITS Pilani, Pilani Campus
Class
[Link]
CS F213 Object Oriented Programming 7
BITS Pilani, Pilani Campus
Class Visibility
• The +, - and # symbols before an attribute and operation
name in a class denote the visibility of the attribute and
operation.
• + denotes public attributes or operations
• - denotes private attributes or operations
• # denotes protected attributes or operations
CS F213 Object Oriented Programming 8
BITS Pilani, Pilani Campus
Parameter Directionality
• Each parameter in an operation (method) may be denoted as
in, out or inout which specifies its direction with respect to the caller. This
directionality is shown before the parameter name.
CS F213 Object Oriented Programming 9
BITS Pilani, Pilani Campus
Inheritance
• A generalization is a taxonomic relationship between a more
general classifier and a more specific classifier.
• Each instance of the specific classifier is also an indirect
instance of the general classifier.
• Represents an "is-a" relationship.
• An abstract class name is shown in italics.
• SubClass1 and SubClass2 are specializations of SuperClass.
CS F213 Object Oriented Programming 10
BITS Pilani, Pilani Campus
Inheritance
CS F213 Object Oriented Programming 11
BITS Pilani, Pilani Campus
Association
• Associations are relationships between classes in a UML Class Diagram.
• They are represented by a solid line between classes.
• Associations are typically named using a verb or verb phrase which
reflects the real world problem domain.
• Simple Association
• A structural link between two peer classes.
• There is an association between Class1 and Class2
• There is an association that connects the <<control>> class Class1 and
<<boundary>> class Class2. The relationship is displayed as a solid line
connecting the two classes.
CS F213 Object Oriented Programming 12
BITS Pilani, Pilani Campus
Cardinality
• Cardinality is expressed in terms of:
1. one to one
2. one to many
3. many to many
CS F213 Object Oriented Programming 13
BITS Pilani, Pilani Campus
Aggregation
• A special type of association.
• It represents a "part of" relationship.
• Class2 is part of Class1.
• Many instances (denoted by the *) of Class2 can be associated with
Class1.
• Objects of Class1 and Class2 have separate lifetimes.
• The relationship is displayed as a solid line with a unfilled diamond at
the association end, which is connected to the class that represents the
aggregate.
CS F213 Object Oriented Programming 14
BITS Pilani, Pilani Campus
Composition
• A special type of aggregation where parts are destroyed when the whole is
destroyed.
• Objects of Class2 live and die with Class1.
• Class2 cannot stand by itself.
• The relationship is displayed as a solid line with a filled diamond at the
association end, which is connected to the class that represents the whole
or composite.
CS F213 Object Oriented Programming 15
BITS Pilani, Pilani Campus
Dependency
• An object of one class might use an object of another class in the code of a
method.
• If the object is not stored in any field, then this is modeled as a dependency
relationship.
• A special type of association.
• Exists between two classes if changes to the definition of one may cause changes
to the other (but not the other way around).
• Class1 depends on Class2
• The relationship is displayed as a dashed line with an open arrow.
CS F213 Object Oriented Programming 16
BITS Pilani, Pilani Campus
Realization(Interfaces)
• Realization is a relationship between the blueprint class and the object
containing its respective implementation level details.
• This object is said to realize the blueprint class.
• In other words, we can understand this as the relationship between the
interface and the implementing class.
• For example, the Owner interface might specify methods for acquiring
property and disposing of property. The Person and Corporation classes
need to implement these methods, possibly in very different ways.
CS F213 Object Oriented Programming 17
BITS Pilani, Pilani Campus
Abstract Classes & Methods
There is an abstract class called Employee. In UML, the name of
an abstract class is written in an italic font. This class contains one
abstract method called calculatePay, it is written in a italic font. An
abstract method has no implementation. Typically an abstract
class contains one or more abstract method. The diagram also
shows three subclasses that inherit behaviour and data attributes
from the Employee class. These are concrete classes that can be
instantiated; abstract classes cannot directly be instantiated
CS F213 Object Oriented Programming 18
BITS Pilani, Pilani Campus
Some Examples
CS F213 Object Oriented Programming 19
BITS Pilani, Pilani Campus
Some Examples
CS F213 Object Oriented Programming 20
BITS Pilani, Pilani Campus
What has been covered?
• UML Notations ✔
CS F213 Object Oriented Programming 21
BITS Pilani, Pilani Campus
Object Oriented Programming
BITS Pilani Dr. Tanmaya Mahapatra
Pilani Campus Department of Computer Science and Information Systems
Contents
• Generics
CS F213 Object Oriented Programming 2
BITS Pilani, Pilani Campus
Generics
• Generics means parameterized types.
• Parameterized types are important because they enable to
create classes, interfaces, and methods in which the type of
data upon which they operate is specified as a parameter.
• Using generics, it is possible to create a single class that
automatically works with different types of data.
• A class, interface, or method that operates on a
parameterized type is called generic, as in generic class or
generic method.
CS F213 Object Oriented Programming 3
BITS Pilani, Pilani Campus
Generics
• It is important to understand that Java has always given the
ability to create generalized classes, interfaces, and methods
by operating through references of type Object.
• Because Object is the superclass of all other classes, an
Object reference can refer to any type object.
• In pre-generics code, generalized classes, interfaces, and
methods used Object references to operate on various types
of objects.
• The problem was with type safety.
• Generics added the type safety that was lacking.
• Demo → ProblemDemo
CS F213 Object Oriented Programming 4
BITS Pilani, Pilani Campus
Generics Demo
• Generics Demo → GenDemo
CS F213 Object Oriented Programming 5
BITS Pilani, Pilani Campus
About T
• In the declaration of Gen, there is no special significance to
the name T.
• Any valid identifier could have been used, but T is traditional.
• It is recommended that type parameter names be single-
character capital letters.
• Other commonly used type parameter names are V and E.
• Beginning with JDK 10, var cannot be used as the name of a
type parameter.
CS F213 Object Oriented Programming 6
BITS Pilani, Pilani Campus
Generics: Reference Types
• When declaring an instance of a generic type, the type
argument passed to the type parameter must be a reference
type.
• We cannot use a primitive type, such as int or char.
• For example, with Gen, it is possible to pass any class type to
T, but the following declaration is illegal:
• Gen<int> intOb = new Gen<int>(53); // Error, can't use
primitive type
• We can use the type wrappers to encapsulate a primitive
type.
• Java’s autoboxing and auto-unboxing mechanism makes the
use of the type wrapper transparent.
CS F213 Object Oriented Programming 7
BITS Pilani, Pilani Campus
Generic Types Differ
• A key point to understand about generic types is that a
reference of one specific version of a generic type is not type
compatible with another version of the same generic type.
• The following line of code is in error and will not compile:
• iOb = strOb; // Wrong!
• Even though both iOb and strOb are of type Gen<T>, they are
references to different types because their type arguments
differ.
• This is part of the way that generics add type safety and
prevent errors.
CS F213 Object Oriented Programming 8
BITS Pilani, Pilani Campus
How it improves Type Safety?
• Example: NonGenDemo
CS F213 Object Oriented Programming 9
BITS Pilani, Pilani Campus
Generic Class with 2 Type Params.
• Demo → SimpleGen
• The generics syntax shown from the demos can be
generalized.
• The syntax for declaring a generic class:
• class class-name<type-param-list > { // …
• Syntax for declaring a reference to a generic class and
instance creation:
• class-name<type-arg-list > var-name = new class-
name<type-arg-list >(cons-arg-list);
CS F213 Object Oriented Programming 10
BITS Pilani, Pilani Campus
Bounded Types
• The type parameters could be replaced by any class type.
• This is fine for many purposes, but sometimes it is useful to
limit the types that can be passed to a type parameter.
• For example, assume that we want to create a generic class
that contains a method that returns the average of an array of
numbers.
• Furthermore, we want to use the class to obtain the average
of an array of any type of number, including integers, floats,
and doubles.
• We want to specify the type of the numbers generically, using
a type parameter.
CS F213 Object Oriented Programming 11
BITS Pilani, Pilani Campus
Traditional Way Fails
CS F213 Object Oriented Programming 12
BITS Pilani, Pilani Campus
Bounded Types
• The average( ) method attempts to obtain the double version
of each number in the nums array by calling doubleValue( ).
• Because all numeric classes, such as Integer and Double, are
subclasses of Number, and Number defines the doubleValue(
) method, this method is available to all numeric wrapper
classes.
• The trouble is that the compiler has no way to know that we
are intending to create Stats objects using only numeric types.
• Compiling Stats → an error is reported that indicates that the
doubleValue( ) method is unknown.
• To solve this problem, we need some way to tell the compiler
that we intend to pass only numeric types to T.
CS F213 Object Oriented Programming 13
BITS Pilani, Pilani Campus
Bounded Types
• We need some way to ensure that only numeric types are actually passed.
• To handle such situations, Java provides bounded types.
• When specifying a type parameter, we can create an upper bound that
declares the superclass from which all type arguments must be derived.
• This is accomplished through the use of an extends clause when
specifying the type parameter:
• <T extends superclass>
• This specifies that T can only be replaced by superclass, or subclasses of
superclass. Thus, superclass defines an inclusive, upper limit.
• We can use an upper bound to fix the Stats class shown earlier by
specifying Number as an upper bound.
• Demo → BoundsDemo
CS F213 Object Oriented Programming 14
BITS Pilani, Pilani Campus
What has been covered?
• Generics ✔
CS F213 Object Oriented Programming 15
BITS Pilani, Pilani Campus
Object Oriented Programming
CS F213
BITS Pilani
Pilani Campus
BITS Pilani
Pilani Campus
Generics (J2SE 5)
Generics
• Similar to templates in C++.
• Allows type to be a parameter to methods, classes and
interfaces
• <> is used to specify the parameter types
• To create objects use the following syntax
BaseType <Type> obj = new BaseType <Type>()
Note: In Parameter type we can not use primitives like
'int','char' or 'double'.
BITS Pilani, Pilani Campus
Advantages
• Type-safety : We can hold only a
single type of objects in generics. It
doesn’t allow to store other objects.
• Type casting is not
required: There is no need to
typecast the object.
• Compile-Time Checking: It is
checked at compile time so
problem will not occur at runtime.
BITS Pilani, Pilani Campus
Generic Class - Example
class Identity<T>{
T obj;
Identity(T obj) { [Link] = obj; }
public T getObject() { return [Link]; }
}
class Test {
public static void main (String[] args) {
Identity <Long> number = new Identity<Long>(9999955555L);
[Link]([Link]());
Identity <String> name = new Identity<String>("Ankit");
[Link]([Link]());
}
}
BITS Pilani, Pilani Campus
• Generics in Java was added to provide type-checking at
compile time and it has no use at run time
• Java compiler uses type erasure feature to remove all the
generics type checking code in byte code and insert type-
casting if necessary.
• Type erasure ensures that no extra classes are created
• Generics incur no runtime overhead.
BITS Pilani, Pilani Campus
Multiple Type Parameters
class Identity<T,U> {
T obj1; U obj2;
Identity(T obj1,U obj2 ) { this.obj1 = obj1;this.obj2 = obj2; }
public void printObject() {
[Link](this.obj1+"\t");[Link](this.obj2); }
}
class Test {
public static void main (String[] args) {
Identity <String, Integer> I1 = new Identity<String,
Integer>("Ankit",20171007);
Identity <Integer,String> I2 = new
Identity<Integer,String>(20171007,"Ankit");
[Link]();
[Link]();
}}
BITS Pilani, Pilani Campus
Generic Functions
class Identity {
public <T> void printObject(T obj) {[Link](obj); }
}
class Test {
public static void main (String[] args) {
Identity I1, I2;
I1 = new Identity();
I2 = new Identity();
[Link](20071007);
[Link]("Ankit");
}
}
BITS Pilani, Pilani Campus
Generic Functions with
generic return type
class Identity {
public <T> T printObject(T obj) {return obj; }
}
class Test {
public static void main (String[] args) {
Identity I1, I2;
I1 = new Identity();
I2 = new Identity();
[Link]([Link](20071007));
[Link]([Link]("Ankit"));
}
}
BITS Pilani, Pilani Campus
Generics in Interfaces
//Generic interface definition
interface DemoInterface<T1, T2> {
T2 doSomeOperation(T1 t);
T1 doReverseOperation(T2 t); }
//A class implementing generic interface
class DemoClass implements DemoInterface<String, Integer>
{
public Integer doSomeOperation(String t)
{
//some code
}
public String doReverseOperation(Integer t)
{
//some code
}
}
BITS Pilani, Pilani Campus
Generic Arrays
• Array in any language have same meaning i.e. an array
is a collection of similar type of elements.
• In java, pushing any incompatible type in an array on
runtime will throw ArrayStoreException.
• It means array preserve their type information in
runtime, and generics use type erasure or remove
any type information in runtime.
• Due to above conflict, instantiating a generic array
in java is not permitted.
BITS Pilani, Pilani Campus
Bound Type with Generics
• Used to restrict the types that can be used as arguments
in a parameterized type.
• Eg: Method operating on numbers should accept the instances of the Number
class or its subclasses.
• Declare a bounded type parameter
• List the type parameter’s name.
• Along by the extends keyword
• And by its upper bound.
BITS Pilani, Pilani Campus
Bound Type - Example
class Identity<T extends Number> {
T obj;
Identity(T obj) { [Link] = obj; }
public T getObject() { return [Link]; }}
class Test {
public static void main (String[] args) {
Identity <Integer> iObj = new Identity<Integer>(20071007);
[Link]([Link]());
Identity <Double> dObj = new Identity<Double>(2007.00);
[Link]([Link]());
Identity <String> sObj = new Identity<String>("Ankit");
[Link]([Link]());
}}
Note: Bound Mismatch: type argument String is not
within bounds of type-variable T
BITS Pilani, Pilani Campus
Type name in Generics
The type name can be named according to programmer’s
convenience. But the common convention is
T - Type
E - Element
K - Key
N - Number
V – Value
Note: Let there be an interface T;
class Identity<T extends T> cannot be done.
BITS Pilani, Pilani Campus
Generics and Inheritance
class MyClass<T>{}
class Main {
public static void main(String[] args) {
String str = "abc";
Object obj = new Object();
obj = str;
// works because String is-a Object (inheritance)
}
}
BITS Pilani, Pilani Campus
Generics and Inheritance
class MyClass<T>{}
class Main {
public static void main(String[] args) {
MyClass<String> myClass1 = new MyClass<String>();
MyClass<Object> myClass2 = new MyClass<Object>();
myClass2 = myClass1;
// compilation error since MyClass<String> is not a MyClass<Object>
}
}
BITS Pilani, Pilani Campus
Generics and Inheritance
class MyClass<T>{}
class Main {
public static void main(String[] args) {
String str = "abc";
Object obj = new Object();
MyClass<String> myClass1 = new MyClass<String>();
MyClass<Object> myClass2 = new MyClass<Object>();
obj = myClass1;
// MyClass<T> parent is Object
}
BITS Pilani, Pilani Campus
What are not allowed with
Generics?
BITS Pilani, Pilani Campus
What are not allowed with
Generics?
BITS Pilani, Pilani Campus
Bounded Types –
Additional Info
class A{
}
• Thus, T is bounded by a
class B{ class A and interface C
and D.
}
• Type argument passed to
interface C{ T must be a subclass of A
and have implemented C
} and D
interface D{
class E<T extends A & C & D>{
BITS Pilani, Pilani Campus
BITS Pilani
Pilani Campus
Introduction to
Collections
What are Collections
• Group of Objects treated as a single Object.
• Java provides supports for manipulating collections in
the form of
– Collection Interfaces
– Collection Classes
• Collection interfaces provide basic functionalities
whereas collection classes provides their concrete
implementation
BITS Pilani, Pilani Campus
Collection Classes
• Collection classes are standard classes that implement
collection interfaces
• Some Collection Classes are abstract and some classes
are concrete and can be used as it is.
• Important Collection Classes:
✔ AbstractCollection
✔ AbstractList
✔ AbstractSequentialList
✔ LinkedList
✔ ArrayList
✔ AbstractSet
✔ HasSet
✔ LinkedHashSet
✔ TreeSet
BITS Pilani, Pilani Campus
Partial View of Collection’s
Framework
BITS Pilani, Pilani Campus
ArrayList - Example
import [Link].*;
class Test{
public static void main(String args[]){
ArrayList<Integer> al1 = new ArrayList<Integer>();
[Link](20);
[Link](9);
ArrayList<Integer> al2 = new ArrayList<Integer>();
[Link](22);
[Link](53);
Output:
[Link](al2); [9, 20, 22, 53]
[Link](al1); 53
[Link](al1);
[Link]([Link](3));}
}
BITS Pilani, Pilani Campus
List Iterator
• List Iterator is used to traverse forward and backward
directions
Method Description
boolean hasNext() This method return true if the list iterator
has more elements when traversing the
list in the forward direction.
Object next() This method return the next element in
the list and advances the cursor position.
boolean hasPrevious() This method return true if this list iterator
has more elements when traversing the
list in the reverse direction.
Object previous() This method return the previous element
in the list and moves the cursor position
backwards.
BITS Pilani, Pilani Campus
List Iterator - Example
ArrayList<Integer> al = new ArrayList<Integer>(); Output:
[Link](20); Forward Traversal
20
[Link](9);
9
[Link](22); 22
[Link](53); 53
Backward Traversal
ListIterator<Integer> itr=[Link](); 53
[Link]("Forward Traversal"); 22
9
while([Link]()) {
20
[Link]([Link]());
}
[Link]("Backward Traversal"); Question: What happens if
while([Link]()) { the backward traversal
[Link]([Link]()); happens before the
forward?
}
BITS Pilani, Pilani Campus
Review Question
ArrayList al = new ArrayList(); Find the output
[Link]("Sachin"); [Link] Error
[Link]("Rahul"); [Link] Error
[Link](10); c.[Sachin, Rahul, 10]
[Sachin, Rahul, 10]
String s[] = new String[3];
for(int i=0;i<3;i++)
s[i] = (String)[Link](i); Note:
No compilation error because
[Link](al); add(Object o) method in the
ArrayList class
[Link]([Link](s)); Runtime Error because integer
object is type case to String
Solution:
Generics
BITS Pilani, Pilani Campus
Array List /Generics -
Review
ArrayList<String> al = new ArrayList<String>();
[Link]("Sachin");
[Link]("Rahul");
Note:
[Link]("10");
Compilation Error if
String s[] = new String[3];
we try to include
for(int i=0;i<3;i++) [Link](10)
s[i] =[Link](i);
[Link](al);
[Link]([Link](s));
BITS Pilani, Pilani Campus
Wildcard in Generics
abstract class Shape{
final double pi = 3.14;
double area;
abstract void draw();
}
class Rectangle extends Shape{
Rectangle(int l,int b){
area = l*b; }
void draw(){[Link]("Area of Rect:"+area);}
}
class Circle extends Shape{
Circle(int r){
area = pi*r*r; }
void draw(){[Link]("Area of circle:"+area);}
}
BITS Pilani, Pilani Campus
Wildcard in Generics
class test{
//creating a method that accepts only child class of Shape
public static void drawShapes(List<? extends Shape> lists){
for(Shape s:lists){
[Link]();}
}
public static void main(String args[]){
List<Rectangle> list1=new ArrayList<Rectangle>(); Output:
[Link](new Rectangle(3,5)); Area of Rect:15.0
Area of circle:12.56
Area of circle:78.5
List<Circle> list2=new ArrayList<Circle>();
[Link](new Circle(2));
[Link](new Circle(5));
drawShapes(list1);
drawShapes(list2);
}}
BITS Pilani, Pilani Campus
Wildcard in Generics
class test{
public static void main(String[] args) {
List<Integer> list1= [Link](1,2,3);
List<Number> list2=[Link](1.1,2.2,3.3);
List<Double> list3=[Link](1.1,2.2,3.3); Output:
List<String> list4=[Link]("s","j","r"); list1, list3, list4 –
compilation error
printlist(list1); Type not applicable for the
printlist(list2); arguements
printlist(list3);
printlist(list4);
}
private static void printlist(List<Number> list) {
[Link](list);
}
}
BITS Pilani, Pilani Campus
Wildcard in Generics
class test{
public static void main(String[] args) {
List<Integer> list1= [Link](1,2,3);
List<Number> list2=[Link](1.1,2.2,3.3);
List<Double> list3=[Link](1.1,2.2,3.3); Output:
List<String> list4=[Link]("s","j","r"); [1, 2, 3]
[1.1, 2.2, 3.3]
printlist(list1); [1.1, 2.2, 3.3]
printlist(list2); [s, j, r]
printlist(list3);
printlist(list4);
}
private static void printlist(List<?> list) {
[Link](list);
}
}
BITS Pilani, Pilani Campus
Upper Bounded Wildcard
class test{
public static void main(String[] args) {
List<Integer> list1= [Link](1,2,3);
List<Number> list2=[Link](1.1,2.2,3.3);
List<Double> list3=[Link](1.1,2.2,3.3); Output:
List<String> list4=[Link]("s","j","r"); list4 – compilation error
Type not applicable for the
printlist(list1); arguements
printlist(list2);
printlist(list3);
printlist(list4);
}
private static void printlist(List<? extends Number> list) {
[Link](list);
}
}
BITS Pilani, Pilani Campus
Lower Bounded Wildcard
class test{
public static void main(String[] args) {
List<Integer> list1= [Link](1,2,3);
List<Number> list2=[Link](1.1,2.2,3.3);
List<Double> list3=[Link](1.1,2.2,3.3); Output:
printlist(list1); list3 – compilation error
printlist(list2); Type not applicable for the
printlist(list3); arguements
}
private static void printlist(List<? super Integer> list) {
[Link](list);
}
}
BITS Pilani, Pilani Campus
BITS Pilani
Pilani Campus
Comparable Interface
Comparable Interface
• It is used to order the objects of user-defined class.
• It is found in [Link] package and contains only one
method named compareTo(Object)
• Elements can be sorted based on single data member eg:
account number, name or age.
• We can sort the elements of:
• String objects
• Wrapper class objects
• User-defined class objects
BITS Pilani, Pilani Campus
Comparable-Example
import [Link].*;
class Account implements Comparable<Account>{
int acc;
String name;
float amt;
Account(int acc,String name,float amt){
[Link] = acc;
[Link] = name;
[Link] = amt; }
public int compareTo(Account ac){
if(amt==[Link])
return 0;
else if(amt>[Link])
return 1;
else
return -1; }
public String toString() {
return "Acc. No.: "+acc+" Name: "+name+" Amount: "+amt;}
}
BITS Pilani, Pilani Campus
Comparable-Example
class Test{
public static void main(String[] args) {
List<Account> al = new ArrayList<Account>();
[Link](new Account(111,"Ankit",5000));
[Link](new Account(112,"Ashok",4000));
[Link](new Account(123,“Ryan",5000));
[Link](al);
for(Account a:al)
[Link](a);
}
}
BITS Pilani, Pilani Campus
BITS Pilani
Pilani Campus
Comparator Interface
Comparator Interface
• Used to order user defined class
• This interface is found in [Link] package and contains
2 methods
• compare(Object obj1,Object obj2)
• equals(Object element)
• It provides multiple sorting sequence
• Elements can be sorted based on any data member
BITS Pilani, Pilani Campus
Comparator - Example
import [Link].*;
class Account{
int acc;
String name;
float amt;
Account(int acc,String name,float amt){
[Link] = acc;
[Link] = name;
[Link] = amt; }
public String toString() {
return "Acc. No.: "+acc+" Name: "+name+" Amount: "+amt;}
}
BITS Pilani, Pilani Campus
Comparator - Example
class AmtCmp implements Comparator<Account>{
public int compare(Account a1,Account a2){
if([Link]==[Link])
return 0;
else if([Link]>[Link])
return 1;
else
return -1; }
}
BITS Pilani, Pilani Campus
Comparator - Example
class AccCmp implements Comparator<Account>{
public int compare(Account a1,Account a2){
if([Link]==[Link])
return 0;
else if([Link]>[Link])
return 1;
else
return -1; }
}
BITS Pilani, Pilani Campus
Comparator - Example
class test {
public static void main(String[] args) {
List<Account> al = new ArrayList<Account>();
[Link](new Account(123,"Ankit",5000));
[Link](new Account(112,"Ashok",4000));
[Link](new Account(111,"Ryan",5000));
[Link]("Comparison on Amount");
[Link](al,new AmtCmp());
for(Account a:al)
[Link](a);
[Link]("Comparison on Acc. No.");
[Link](al,new AccCmp());
for(Account a:al)
[Link](a); }
}
BITS Pilani, Pilani Campus
Overriding Equals method
class Account implements Comparator<Account>{
int acc;
String name;
float amt;
Account(int acc,String name,float amt){
[Link] = acc;
[Link] = name;
[Link] = amt; }
public boolean equals(Account a1) {
if (a1 == null)
return false;
if([Link] != [Link])
return false;
if([Link] != [Link])
return false;
if(!([Link]([Link])))
return false;
return true;} BITS Pilani, Pilani Campus
Overriding Equals method
public String toString() {
return "Acc. No.: "+acc+" Name: "+name+" Amount: "+amt;}
public int compare(Account arg0, Account arg1) {
// TODO Auto-generated method stub
return 0;}
}
class test {
public static void main(String[] args) {
List<Account> al = new ArrayList<Account>();
[Link](new Account(111,"Ryan",5000));
[Link](new Account(112,“Ryan",5000));
[Link](new Account(111,"Ryan",5000));
[Link]([Link](0).equals([Link](2)));
[Link]([Link](0).equals([Link](1))); }
}
BITS Pilani, Pilani Campus
Bounds in Generics
(Comparator)
public class test {
public static void main(String[] args) {
[Link]("Max of %d, %d and %d is %d\n\n",
3, 4, 5, maximum( 3, 4, 5 ));
[Link]("Max of %.1f,%.1f and %.1f is %.1f\n\n",
6.6, 8.8, 7.7, maximum( 6.6, 8.8, 7.7 ));
[Link]("Max of %s,%s and %s is %s\n\n",
"s", "j", "r", maximum( "s", "j", "r" ));
}
public static <T extends Comparable<T>> T maximum(T x, T y, T z) {
T max = x;
if([Link](max) > 0) { Output:
max = y; } Max of 3, 4 and 5 is 5
if([Link](max) > 0) { Max of 6.6,8.8 and 7.7 is 8.8
Max of s,j and r is s
max = z; }
return max; }
} BITS Pilani, Pilani Campus
Multiple Bounds in
Generics
public class test {
public static void main(String[] args) {
[Link]("Max of %d, %d and %d is %d\n\n",
3, 4, 5, maximum( 3, 4, 5 ));
[Link]("Max of %.1f,%.1f and %.1f is %.1f\n\n",
6.6, 8.8, 7.7, maximum( 6.6, 8.8, 7.7 ));
[Link]("Max of %s,%s and %s is %s\n\n",
"s", "j", "r", maximum( "s", "j", "r" ));
}
public static <T extends Number & Comparable<T>> T maximum(T x, T
y, T z) {
T max = x; Error:
if([Link](max) > 0) { The method maximum(T, T, T)
max = y; } in the type test is not
if([Link](max) > 0) { applicable for the arguments
(String, String, String)
max = z; }
return max; } } BITS Pilani, Pilani Campus
BITS Pilani
Pilani Campus
Coming back to
Collections
ArrayList
• Growable Array implementation of List interface.
• Insertion order is preserved.
• Duplicate elements are allowed.
• Multiple null elements of insertion are allowed.
• Default initial capacity of an ArrayList is 10.
• The capacity grows with the below formula, once ArrayList
reaches its max capacity.
• newCapacity= (oldCapacity * 3)/2 + 1
• When to use?
• If elements are to be retrieved frequently. Because ArrayList implements
RandomAccess Interface
• When not to use?
• If elements are added/removed at specific positions frequently
BITS Pilani, Pilani Campus
LinkedList
• Linked list is implementation class of List interface.
• Underlying data structure is Double linked list.
• Insertion order is preserved.
• Duplicate elements are allowed.
• Multiple null elements of insertion are allowed.
BITS Pilani, Pilani Campus
LinkedList - Methods
Constructor/Method Description
List list = new LinkedList(); It creates an empty linked list.
public boolean add(E e); It adds the specified element at the end of
the list.
public void addFirst(E e); It adds the specified element in the beginni
ng of the list.
public void addLast(E e); It adds the specified element to the end of
the list
public E removeFirst(); It removes and returns the first element fr
om the list.
public E removeLast(); It removes and returns the last element fro
m the list.
public E getFirst(); It returns the first element from the list.
public E getLast(); It returns the last element from the list.
BITS Pilani, Pilani Campus
Iterator vs. ListIterator
BITS Pilani, Pilani Campus
Stack
• Stack is child class of Vector
• Stack class in java represents LIFO (Last in First Out) stack of
objects.
Method Description
public E push(E item); Pushes the item on top of the stack
public synchronized E pop(); Removes the item at the top of the stack
and returns that item
public synchronized E peek(); Returns the item at the top of the stack
public boolean empty(); Checks whether stack is empty or not
public synchronized int search Returns the position of an object in the
(Object o); stack.
BITS Pilani, Pilani Campus
BITS Pilani
Pilani Campus
Set Interface
Set Interface
• The set interface is an unordered collection of objects in
which duplicate values cannot be stored.
• The Java Set does not provide control over the position
of insertion or deletion of elements.
• Basically, Set is implemented
by HashSet, LinkedHashSet or TreeSet (sorted
representation).
BITS Pilani, Pilani Campus
HashSet
• Implements Set Interface.
• Underlying data structure for HashSet is hashtable.
• As it implements the Set Interface, duplicate values are not
allowed.
• Objects that you insert in HashSet are not guaranteed to be
inserted in same order. Objects are inserted based on their
hash code.
• NULL elements are allowed in HashSet.
• Execution time of add(), contains(), remove(), size() is
constant even for large sets.
BITS Pilani, Pilani Campus
HashSet - Example
HashSet<Integer> set = new HashSet<Integer>();
[Link](12);
[Link](63);
[Link](34);
Output:
[Link](45);
Set data: 34 12 45 63
[Link](12);
Iterator<Integer> iterator = [Link]();
[Link]("Set data: ");
while ([Link]()) {
[Link]([Link]() + " ");
}
BITS Pilani, Pilani Campus
Equivalent Code JDK 7+
Local Variable Type Inference
Type Inference: Argument Passing
Erasure
• It is not necessary to know the details about how the Java compiler
transforms the source code into object code.
• However, in the case of generics, some general understanding of the
process is important because it explains why the generic features
work as they do—and why their behavior is sometimes a bit
surprising.
Erasure
• An important constraint that governed the way that generics were
added to Java was the need for compatibility with previous versions
of Java.
• Generic code had to be compatible with preexisting, non-generic
code.
• Thus, any changes to the syntax of the Java language, or to the JVM,
had to avoid breaking older code.
• The way Java implements generics while satisfying this constraint is
through the use of erasure.
Erasure
• When the Java code is compiled, all generic type information is
removed (erased).
• This means replacing type parameters with their bound type, which is
Object if no explicit bound is specified, and then applying the
appropriate casts (as determined by the type arguments) to maintain
type compatibility with the types specified by the type arguments.
• The compiler also enforces this type compatibility.
• This approach to generics means that no type parameters exist at run
time.
• They are simply a source-code mechanism.
Bridge Methods
• The compiler will need to add a bridge method to a class to handle
situations in which the type erasure of an overriding method in a
subclass does not produce the same erasure as the method in the
superclass.
• In this case, a method is generated that uses the type erasure of the
superclass, and this method calls the method that has the type
erasure specified by the subclass.
• Bridge methods only occur at the bytecode level, are not seen by
you, and are not available for our use.
Covariant Type
• Java supports* covariant return types for overridden methods.
• This means an overridden method may have a more specific return
type.
• That is, as long as the new return type is assignable to the return type
of the method you are overriding, it's allowed.
• Prior to Java 5, Java had invariant return types, which meant the
return type of a method override needed to exactly match the
method being overridden.
Covariant Type
Object Oriented Programming
BITS Pilani Dr. Tanmaya Mahapatra
Pilani Campus Department of Computer Science and Information Systems
Contents
• Maps
• Comparators
• Wrapper Classes
CS F213 Object Oriented Programming 2
BITS Pilani, Pilani Campus
Maps
• A map is an object that stores associations between keys and
values, or key/value pairs.
• Given a key, we can find its value.
• Both keys and values are objects.
• The keys must be unique, but the values may be duplicated.
• Some maps can accept a null key and null values, others cannot.
• Maps don’t implement the Iterable interface.
• We cannot cycle through a map using a for-each style for loop.
• can’t obtain an iterator to a map.
• Can obtain a collection-view of a map, which does allow the use of
either the for loop or an iterator.
CS F213 Object Oriented Programming 3
BITS Pilani, Pilani Campus
Maps Interfaces
CS F213 Object Oriented Programming 4
BITS Pilani, Pilani Campus
The Map Interface
• The Map interface maps unique keys to values.
• A key is an object that can be used to retrieve a value at a
later date.
• Given a key and a value, we can store the value in a Map
object. After the value is stored, we can retrieve it by using its
key.
• Map is generic :
• interface Map<K, V>
• K specifies the type of keys, and V specifies the type of values.
CS F213 Object Oriented Programming 5
BITS Pilani, Pilani Campus
The Map Interface
• Maps revolve around two basic operations: get( ) and put( ).
• To put a value into a map, → put( ), specifying the key and the value.
• To obtain a value → get( ), passing the key as an argument. The value is
returned.
• Although part of the Collections Framework, maps are not, themselves,
collections because they do not implement the Collection interface.
• We can obtain a collection-view of a map.
• To do this → use the entrySet( ) method. It returns a Set that contains the
elements in the map.
• To obtain a collection-view of the keys → keySet( ).
• To get a collection-view of the values → values( ).
• For all three collection-views, the collection is backed by the map.
Changing one affects the other. Collection-views are the means by which
maps are integrated into the larger Collections Framework.
CS F213 Object Oriented Programming 6
BITS Pilani, Pilani Campus
The SortedMap Interface
• The SortedMap interface extends Map. It ensures that the entries are
maintained in ascending order based on the keys.
• SortedMap is generic:
• interface SortedMap<K, V>
• K specifies the type of keys, and V specifies the type of values.
CS F213 Object Oriented Programming 7
BITS Pilani, Pilani Campus
The SortedMap Interface
• Sorted maps allow very efficient manipulations of submaps.
• To obtain a submap → headMap( ), tailMap( ), or subMap( ).
• The submap returned by these methods is backed by the
invoking map.
• Changing one changes the other.
• To get the first key in the set → firstKey( ).
• To get the last key → lastKey( ).
CS F213 Object Oriented Programming 8
BITS Pilani, Pilani Campus
The NavigableMap Interface
• The NavigableMap interface extends SortedMap and declares
the behavior of a map that supports the retrieval of entries
based on the closest match to a given key or keys.
• NavigableMap is a generic
• interface NavigableMap<K,V>
• K specifies the type of the keys, and V specifies the type of
the values associated with the keys.
CS F213 Object Oriented Programming 9
BITS Pilani, Pilani Campus
The [Link] Interface
• The [Link] Interface interface enables to work with a map
entry.
• For example → the entrySet( ) method declared by the Map
interface returns a Set containing the map entries.
• Each of these set elements is a [Link] object.
• [Link] is generic:
• interface [Link]<K, V>
• Imp Static Methods:
• comparingByKey( ), which returns a Comparator that compares
entries by key.
• comparingByValue( ), which returns a Comparator that compares
entries by value.
CS F213 Object Oriented Programming 10
BITS Pilani, Pilani Campus
The [Link] Interface
CS F213 Object Oriented Programming 11
BITS Pilani, Pilani Campus
Map Classes
CS F213 Object Oriented Programming 12
BITS Pilani, Pilani Campus
The HashMap Class
• The HashMap class extends AbstractMap and implements the Map
interface.
• It uses a hash table to store the map.
• This allows the execution time of get( ) and put( ) to remain constant even
for large sets.
• HashMap is a generic class:
• class HashMap<K, V>
• K specifies the type of keys, and V specifies the type of values.
• The following constructors are defined:
• HashMap( )
• HashMap(Map<? extends K, ? extends V> m)
• HashMap(int capacity)
• HashMap(int capacity, float fillRatio)
CS F213 Object Oriented Programming 13
BITS Pilani, Pilani Campus
The HashMap Class
• The first form constructs a default hash map.
• The second form initializes the hash map by using the elements of m.
• The third form initializes the capacity of the hash map to capacity.
• The fourth form initializes both the capacity and fill ratio of the hash map by using
its arguments. The meaning of capacity and fill ratio is the same as for HashSet,
described earlier. The default capacity is 16. The default fill ratio is 0.75.
• HashMap implements Map and extends AbstractMap. It does not add any
• methods of its own.
• A hash map does not guarantee the order of its elements.
• Therefore, the order in which elements are added to a hash map is not necessarily
the order in which they are read by an iterator.
• Demo
CS F213 Object Oriented Programming 14
BITS Pilani, Pilani Campus
TreeMap Class
• The TreeMap class extends AbstractMap and implements the NavigableMap
• interface. I
• t creates maps stored in a tree structure.
• A TreeMap provides an efficient means of storing key/value pairs in sorted order
and allows rapid retrieval.
• Unlike a hash map, a tree map guarantees that its elements will be sorted in
ascending key order. TreeMap is a generic class that has this declaration:
• class TreeMap<K, V>
• K specifies the type of keys, and V specifies the type of values.
• The following TreeMap constructors are defined:
• TreeMap( )
• TreeMap(Comparator<? super K> comp)
• TreeMap(Map<? extends K, ? extends V> m)
• TreeMap(SortedMap<K, ? extends V> sm)
• Demo
CS F213 Object Oriented Programming 15
BITS Pilani, Pilani Campus
Comparator
• Both TreeSet and TreeMap store elements in sorted order.
• However, it is the comparator that defines precisely what “sorted order”
means. By default, these classes store their elements by using what Java
refers to as “natural ordering,” which is usually the ordering that we would
expect (A before B, 1 before 2, and so forth).
• If we want to order elements a different way, then specify a Comparator
when we construct the set or map.
• Doing so gives us the ability to govern precisely how elements are stored
within sorted collections and maps.
• Comparator is a generic interface that has this declaration:
• interface Comparator<T>
• T specifies the type of objects being compared.
CS F213 Object Oriented Programming 16
BITS Pilani, Pilani Campus
What has been covered?
• Collection Classes : ArrayList ✔
• LinkedList ✔
• HashSet & LinkedHashSet ✔
• TreeSet & ArrayDeque ✔
• Iterators & ListInterator ✔
• For-Each Alternative ✔
• Storing Objects of Custom Classes in Collections ✔
CS F213 Object Oriented Programming 17
BITS Pilani, Pilani Campus