of 39
8/16/2019 Collection Aima
1/39
ADT
We can further extend the meaning of the ADT when applying itto data structures such as a stack and queue. In Java as with anyclass it means the data and the operations that can !e performedon it. In this context although even the fundamentals of how thedata is stored should !e invisi!le to the user. "sers not only
should not know how the methods work they should also notknow what structures are !eing used to store the data. #onsider for example the stack class. The end user knows that
push$% and pop$% $amoung other similar methods% exist and howthey work. The user doesn&t and shouldn&t have to know how
push$% and pop$% work or whether data is stored in an array alinked list or some other data structure like a tree.
8/16/2019 Collection Aima
2/39
8/16/2019 Collection Aima
3/39
Java #ollection *ramework
Java collections framework The Java collections framework $J#*% is a set of classes and
interfaces that implement commonly reusa!le collection
data structures.+,-
Although it is a framework it works in a manner of a library. The J#* provides !oth
,. Interfaces that define various collections and . #lasses that implement them.
The #ollections *ramework provides a well/designed set ofinterfaces and classes for storing and manipulating groups of data asa single unit a collection.
http://en.wikipedia.org/wiki/Java_programming_languagehttp://en.wikipedia.org/wiki/Class_%28computer_science%29http://en.wikipedia.org/wiki/Interface_%28java%29http://en.wikipedia.org/wiki/Data_structurehttp://en.wikipedia.org/wiki/Java_collections_frameworkhttp://en.wikipedia.org/wiki/Software_frameworkhttp://en.wikipedia.org/wiki/Software_frameworkhttp://en.wikipedia.org/wiki/Java_collections_frameworkhttp://en.wikipedia.org/wiki/Data_structurehttp://en.wikipedia.org/wiki/Interface_%28java%29http://en.wikipedia.org/wiki/Class_%28computer_science%29http://en.wikipedia.org/wiki/Java_programming_language
8/16/2019 Collection Aima
4/39
4
8/16/2019 Collection Aima
5/39
8/16/2019 Collection Aima
6/39
Java collection framework
The #ollection *ramework provides a set of interfacesand classes for represnting groups of data as an
a!straction called a #ollection.
(ava.util is a package Java.util.#ollection is the interface that is !ase of all
the interfaces of collection that expose operations like
adding removing and querying.
Java.util.A!stract#ollection is class that the foundationof all the #ollection framework classes. 3ee the figure
in next slide
8/16/2019 Collection Aima
7/39
4ou can see #ollection interface is the !ase of another
interfaces like set list etc.
And A!stract#ollection class the !ase of another collection
class like A!stract5ist A!stract3et etc.
8/16/2019 Collection Aima
8/39
8/16/2019 Collection Aima
9/39
8/16/2019 Collection Aima
10/39
Dynamic :inding
$late !inding virtual !inding% A mechanism !y which when the compiler can&t
determine which method implementation to use in
advance the runtime system $J;
8/16/2019 Collection Aima
11/39May 24, 201
Introduction to #ollections
8/16/2019 Collection Aima
12/3912
#ollections
A collection is a structured group of o!(ects
Java ,. introduced the #ollections *ramework #ollections are defined in java.util
The #ollections framework is mostly a!out interfaces There are a num!er of predefined implementations
Java 0 introduced generics and =generici)ed> all the
existing collections Vectors have !een redefined to implement Collection
Trees linked lists stacks hash ta!les and other classes are
implementations of Collection
Arrays do not implement the Collection interfaces
8/16/2019 Collection Aima
13/3913
Types of #ollection
Java supplies several types of Collection? Set? cannot contain duplicate elements order is not important SortedSet? like a Set !ut order is important List? may contain duplicate elements order is important
Java also supplies some =collection/like> things? Map? a =dictionary> that associates keys with values order is not
important
SortedMap? like a Map !ut order is important
While you can get all the details from the Java A2I you are
expected to learn $i.e. memorize%? The signatures of the =most important> methods in each interface
The most important implementations of each interface
8/16/2019 Collection Aima
14/3914
The #ollections hierarchy
8/16/2019 Collection Aima
15/39
SOFTENG 251
Ob ect Oriented
15
Interfaces
Root interface for operations
common to all types of collections
Specialises collection with
operations for FIFO and priority
queues.
Stores a sequence of elements,
allowing indexing methods
A special
Collection that
cannot contain
duplicates.
Special Set that retains
ordering of elements.
Stores mappings from keys to
values
Special map in
which keys are
ordered
Generalisation
Specialisation
Collection
Set List Queue
SortedSet
Map
SortedMap
8/16/2019 Collection Aima
16/39
8/16/2019 Collection Aima
17/391#
The Collection interface
8/16/2019 Collection Aima
18/391$
The "terator interface
An iterator is an o!(ect that will return the elements of acollection one at a time
interface Iterator boolean hasNext()
1eturns true if the iteration has more elements
E next() 1eturns the next element in the iteration
void remove() 1emoves from the underlying collection the last element returned !y
the iterator $optional operation%
8/16/2019 Collection Aima
19/391%
The Set interface
A set is a collection in which? There are no duplicate elements $according to equals% and @rder is not important
interface Set implements Collection, Iterable
The methods of Set are exactly the ones in Collection The following methods are especially interesting?
boolean contains(b!ect o) "" membership test boolean contains#ll(Collection c) ""subset test boolean add#ll(Collection c) "" union
boolean retain#ll(Collection c) "" intersection boolean remove#ll(Collection c) "" difference
add#ll retain#ll and remove#ll return true if the receiving setis changed and false otherwise
8/16/2019 Collection Aima
20/3920
The List interface
A list is an ordered sequence of elements interface %ist extends Collection, Iterable 3ome important %ist methods are?
void add(int index, E element)
E remove(int index) boolean remove(b!ect o) E set(int index, E element) E &et(int index) int indexf(b!ect o)
int lastIndexf(b!ect o) %istIterator listIterator()
A %istIterator is like an Iterator !ut has in addition has'revious andprevious methods
8/16/2019 Collection Aima
21/39
Collection Iterate Example
hasnext$% and next$% In this section you will get the detailed explanation
a!out the next() method of interface Iterator. We are
going to use next() method of interface Iterator in Java.
The description of the code is given !elow for the usage
of the method.
21
8/16/2019 Collection Aima
22/39
In the program code given !elow we have taken a string of elements. We have
converted this string of elements into a list of array and then we have applied the hasNext( method which returns true !ecause there are more elements in the list.
ence we get the following output.
import !ava."til.#$
p"blic class hasNext%
p"blic static void main (&trin' ar's) %
boolean b$
&trin' elements) * %+,l"e+- +rey+- +/eal+0$
&et s * new 1ash&et(Arrays.asList(elements$
Iterator i * s.iterator($
if (b * i.hasNext(%
&ystem.o"t.println(b$
0
0
0
22
C23"ni4"e5!avac hasNext.!ava
C23"ni4"e5!ava hasNext
tr"e
C23"ni4"e5
8/16/2019 Collection Aima
23/39
In the program code given !elow we have taken a stringof elements. We have converted this string of elements
into a list of array and then we have applied the
hasNext( method first which will check if there is
another element or not and if there exist another element
then it will return that $next element% with the help of
next() method. ence we get the following output.
23
8/16/2019 Collection Aima
24/39
import (ava.util.B9
p"blic class nextC
p"blic static void main $3tring args+-% C
3tring elements+- 8 C:lue Erey TealF9 3et s 8 new ash3et$Arrays.as5ist$elements%%9
Iterator i 8 s.iterator$%9
while $i.hasGext$%% C
3ystem.out.println$i.next$%%9 F
F
F
24
8/16/2019 Collection Aima
25/39
C23"ni4"e5!avac next.!ava
C23"ni4"e5!ava next
,l"e
rey
/eal
C23"ni4"e5
25
8/16/2019 Collection Aima
26/39
26
The SortedSet interface
A SortedSet is a Set for which the order of elements is important
interface SortedSet
implements Set, Collection, Iterable
Two of the SortedSet methods are? E first()
E last()
8/16/2019 Collection Aima
27/39
2#
The Map interface
A map is a data structure for associating keys and values Interface ap
The two most important methods are? * put( +e, * value) adds a key/value pair to the map
* &et(b!ect +e) given a key looks up the associated value 3ome other important methods are?
Set +eSet() 1eturns a set view of the keys contained in this map.
Collection values() 1eturns a collection view of the values contained in this map
8/16/2019 Collection Aima
28/39
2$
The SortedMap interface
A sorted map is a map that keeps the keys in sorted order Interface Sortedap
Two of the Sortedap methods are? firste()
laste()
8/16/2019 Collection Aima
29/39
2%
Eenerics
public interface List {
void add(E x);
Iterator iterator();
public interface Iterator {
E next();
boolean !as"ext();
public interface #ap {
& put($ 'ey% & value);
Example 1 – Defining Generic Types:
8/16/2019 Collection Aima
30/39
30
Why generic programming:ackground
old version ,. Java collections were Object /!ased andrequired the use of ugly casts cannot specify the exact type of elements
must cast to specific classes when accessing
Java generics
lets you write code that is safer and easier to read
is especially useful for general data structures such as
Array5ist
generic programming 8 programming with classes and
methods parameteri)ed with types
8/16/2019 Collection Aima
31/39
31
Why generic programming $cont.% generic types are a powerful tool to write reusa!le o!(ect/
oriented components and li!raries however the generic language features are not easy to
master and can !e misused
their full understanding requires the knowledge of the typetheory of programming languages especially covariant and contravariant typing
the following introduces the main aspects of Java generics
and their use and limitations we mostly inspect illustrative samples of what is and what
is not allowed with some short glimpses inside the J;<
implementation
8/16/2019 Collection Aima
32/39
32
Why generic programming $cont.%Java generics
in principle supports statically-tyed data structures early detection of type violations
cannot insert a string into Array5ist 6Gum!er7
also hides automatically generated casts suerficially resem!les #KK templates
#KK templates are factories for ordinary classes and
functions a new class is always instantiated for given distinct generic
parameters $type or other%
in Java generic types are factories for comile-time
entities related to types and methods
8/16/2019 Collection Aima
33/39
33
Definition of a simple generic class class 2air 6T7 C
pu!lic T first9 pu!lic T second9
pu!lic 2air $T f T s% C first 8 f9 second 8 s9 F
pu!lic 2air $% C first 8 null9 second 8 null9 F
F you instantiate the generic class !y su!stituting actual
types for type varia!les as? 2air 63tring7
you can think the result as a class with a constructor pu!lic 2air $3tring f 3tring s% etc . .
you can then use the instantiated generic class as it
were a normal class $almost%?2air 63tring7 pair 8 new 2air 63tring7 $,%9
8/16/2019 Collection Aima
34/39
8/16/2019 Collection Aima
35/39
35
Which #ollections do we haveL
There are two main interfaces for all the collection
types in Java:
Collection
ap
8/16/2019 Collection Aima
36/39
36
#ollection "tils
,an%f*l Collection *tils appears as static metho%sof the class Collections:
http:''(ava)s*n)com'(avase'+'%ocs'api'(ava'*til'Collections)html
- similar set of *tils for simple arrays appear in the
class -rrays:
http:''(ava)s*n)com'(avase'+'%ocs'api'(ava'*til'-rrays)html
8/16/2019 Collection Aima
37/39
3#
1estrictions and limitations in Java generic types are comile-time entities
in #KK instantiations of a class template are comiled searately as source code and tailored code is produced for
each one
primitive type parameters $2air 6int7% not allowed in #KK !oth classes and primitive types allowed
o!(ects in J;< have non/generic classes?2air63tring7 str2air 8 new 2air63tring7 . .9
2air6Gum!er7 num2air 8 new 2air6Gum!er7 . .9 ! 8 str2air.get#lass $% 88 num2air.get#lass $%9
assert ! 88 true9 !oth of the raw class 2air
!ut !yte/code has reflective info a!out generics
8/16/2019 Collection Aima
38/39
3$
3ome implementations
class -ashSet implements Set class .reeSet implements SortedSet class #rra%ist implements %ist class %in+ed%ist implements %ist
class *ector implements %ist class Stac+ extends *ector
Important methods? push pop pee+ isEmpt
class -ashap implements ap class .reeap implements Sortedap
All of the a!ove provide a no/argument constructor
8/16/2019 Collection Aima
39/39
The Mnd