You are on page 1of 39

ADT

We can further extend the meaning of the ADT when applying it


to data structures such as a stack and queue. In Java, as with any
class, it means the data and the operations that can be performed
on it. In this context, although, even the fundamentals of how the
data is stored should be invisible to the user. Users not only
should not know how the methods work, they should also not
know what structures are being used to store the data.
Consider for example the stack class. The end user knows that
push() and pop() (amoung other similar methods) exist and how
they work. The user doesn't and shouldn't have to know how
push() and pop() work, or whether data is stored in an array, a
linked list, or some other data structure like a tree.

Collection

Collections
A collection sometimes called a container is
simply an object that groups multiple elements into a
single unit(called container). Collections are used to
store, retrieve, manipulate, and communicate aggregate
(group of data)data.
Collection's works a bit like arrays, except their size can
change dynamically, and they have more advanced
behaviour than arrays.

Java Collection Framework

Java collections framework


The Java collections framework (JCF) is a set of classes and
interfaces that implement commonly reusable collection
data structures.[1]
Although it is a framework, it works in a manner of a library.
The JCF provides both

1. Interfaces that define various collections and

2. Classes that implement them.

The Collections Framework provides a well-designed set of


interfaces and classes for storing and manipulating groups of data as
a single unit, a collection.

Collections Framework

Reduces the effort required to learn APIs


Reduces the effort required to design and implement
APIs
Set and List are subinterfaces of Collection.

Java collection framework

The Collection Framework provides a set of interfaces


and classes for represnting groups of data as an
abstraction called a Collection.
java.util is a package
Java.util.Collection is the interface that is base of all
the interfaces of collection that expose operations like
adding, removing and querying.
Java.util.AbstractCollection is class that the foundation
of all the Collection framework classes. See the figure
in next slide

You can see Collection interface is the base of another


interfaces like set, list etc.
And AbstractCollection class the base of another collection
class like AbstractList , AbstractSet etc.

Java.util.Collection interface

A Java collection is any class that holds objects and implements the Collection
interface

For example, the ArrayList<T> class is a Java collection class, and implements all the methods
in the Collection interface
This idiom creates a new ArrayList (an implementation of the List interface), initially containing
all the elements in c.
List<String> list = new ArrayList<String>(c);
List is the interface
ArralyList is the class that can implement of method of List interface.

The Collection interface is the highest level of Java's framework for collection
classes

All of the collection classes discussed here can be found in package java.util

Dynamic Binding
(late binding, virtual binding)

A mechanism by which, when the compiler can't


determine which method implementation to use in
advance, the runtime system (JVM) selects the
appropriate method at runtime, based on the class of the
object .
The process of binding a call to a particular method.
This is performed dynamically at run-time due to the
presence of polymorphism

Introduction to Collections

May 24, 201

Collections

A collection is a structured group of objects

Java 1.2 introduced the Collections Framework

Collections are defined in java.util


The Collections framework is mostly about interfaces
There are a number of predefined implementations

Java 5 introduced generics and genericized all the


existing collections

Vectors have been redefined to implement Collection


Trees, linked lists, stacks, hash tables, and other classes are
implementations of Collection
Arrays do not implement the Collection interfaces
12

Types of Collection

Java supplies several types of Collection:

Java also supplies some collection-like things:

Set: cannot contain duplicate elements, order is not important


SortedSet: like a Set, but order is important
List: may contain duplicate elements, order is important
Map: a dictionary that associates keys with values, order is not
important
SortedMap: like a Map, but order is important

While you can get all the details from the Java API, 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

13

The Collections hierarchy

14

Generalisation

Interfaces
Aspecial
Collectionthat
cannotcontain
duplicates.

Set

SortedSet

Rootinterfaceforoperations
commontoalltypesofcollections

Storesmappingsfromkeysto
values

Collection

List

Map

SortedMap

Queue
Specialisescollectionwith
operationsforFIFOandpriority
queues.

Specialmapin
whichkeysare
ordered

Storesasequenceofelements,
allowingindexingmethods
SpecialSetthatretains
orderingofelements.

Specialisation
15 251
SOFTENG
Object Oriented

Collections are ADTs

Collections are one of the best-designed parts of Java,


because

They are elegant: they combine maximum power with


maximum simplicity
They are uniform: when you know how to use one, you
almost know how to use them all
You can easily convert from one to another

16

The Collection interface

Much of the elegance of the Collections Framework arises


from the intelligent use of interfaces
The Collection interface specifies (among many other
operations):

boolean add(E o)
boolean contains(Object o)
boolean remove(Object o)
boolean isEmpty()
int size()
Object[] toArray()
Iterator<E> iterator()

You should learn all the methods of the Collection


interface--all are important
17

The Iterator interface

An iterator is an object that will return the elements of a


collection, one at a time
interface Iterator<E>

boolean hasNext()

E next()

Returns true if the iteration has more elements


Returns the next element in the iteration

void remove()

Removes from the underlying collection the last element returned by


the iterator (optional operation)

18

The Set interface

A set is a collection in which:

interface Set<E> implements Collection, Iterable


The methods of Set are exactly the ones in Collection
The following methods are especially interesting:

There are no duplicate elements (according to equals), and


Order is not important

boolean contains(Object o)
boolean containsAll(Collection<?> c)
boolean addAll(Collection<? extends E> c)
boolean retainAll(Collection<?> c)
boolean removeAll(Collection<?> c)

// membership test
//subset test
// union
// intersection
// difference

addAll, retainAll, and removeAll return true if the receiving set


is changed, and false otherwise
19

The List interface

A list is an ordered sequence of elements


interface List<E> extends Collection, Iterable
Some important List methods are:

void add(int index, E element)


E remove(int index)
boolean remove(Object o)
E set(int index, E element)
E get(int index)
int indexOf(Object o)
int lastIndexOf(Object o)
ListIterator<E> listIterator()

A ListIterator is like an Iterator, but has, in addition, hasPrevious and


previous methods

20

Collection Iterate Example


hasnext() and next()

In this section, you will get the detailed explanation


about 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 below for the usage
of the method.

21

In the program code given below, 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 because there are more elements in the list.
Hence we get the following output.
import java.util.*;
public class hasNext{
public static void main (String args[]) {
boolean b;
String elements[] = {"Blue", "Grey", "Teal"};
Set s = new HashSet(Arrays.asList(elements));
Iterator i = s.iterator();
if (b = i.hasNext()){
System.out.println(b);
}
}
}

C:\unique>javac hasNext.java
C:\unique>java hasNext
true
C:\unique>

22

In the program code given below, 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 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. Hence we get the following output.

23

import java.util.*;
public class next{
public static void main (String args[]) {
String elements[] = {"Blue", "Grey", "Teal"};
Set s = new HashSet(Arrays.asList(elements));
Iterator i = s.iterator();
while (i.hasNext()) {
System.out.println(i.next());
}
}
}
24

C:\unique>javac next.java
C:\unique>java next
Blue
Grey
Teal
C:\unique>

25

The SortedSet interface

A SortedSet is a Set for which the order of elements is


important
interface SortedSet<E>
implements Set, Collection, Iterable
Two of the SortedSet methods are:

E first()
E last()

More interestingly, only Comparable elements can be added to a


SortedSet, and the sets Iterator will return these in sorted
order
The Comparable interface is covered in a separate lecture

26

The Map interface

A map is a data structure for associating keys and values


Interface Map<K,V>
The two most important methods are:

V put(K key, V value) // adds a key-value pair to the map


V get(Object key) // given a key, looks up the associated value

Some other important methods are:

Set<K> keySet()

Returns a set view of the keys contained in this map.

Collection<V> values()

Returns a collection view of the values contained in this map

27

The SortedMap interface

A sorted map is a map that keeps the keys in sorted order


Interface SortedMap<K,V>
Two of the SortedMap methods are:

K firstKey()
K lastKey()

More interestingly, only Comparable elements can be used as


keys in a SortedMap, and the method Set<K> keySet() will
return a set of keys whose iterator will return them sorted order
The Comparable interface is covered in a separate lecture

28

Generics
Example 1 Defining Generic Types:
public interface List<E> {
void add(E x);
Iterator<E> iterator();
}
public interface Iterator<E> {
E next();
boolean hasNext();
}
public interface Map<K,V> {
V put(K key, V value);
}
29

Why generic programming


Background
old version 1.4 Java collections were Object-based and
required 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
ArrayList

generic programming = programming with classes and


methods parameterized with types
30

Why generic programming (cont.)

generic types are a powerful tool to write reusable objectoriented components and libraries
however, the generic language features are not easy to
master and can be misused

their full understanding requires the knowledge of the type


theory 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 JVM
implementation
31

Why generic programming (cont.)


Java generics

in principle, supports statically-typed data structures

early detection of type violations

also, hides automatically generated casts

superficially resembles C++ templates

C++ templates are factories for ordinary classes and


functions

cannot insert a string into ArrayList <Number>

a new class is always instantiated for given distinct generic


parameters (type or other)

in Java, generic types are factories for compile-time


entities related to types and methods
32

Definition of a simple generic class


class Pair <T> {
public T first;
public T second;
public Pair (T f, T s) { first = f; second = s; }
public Pair () { first = null; second = null; }
}

you instantiate the generic class by substituting actual


types for type variables, as: Pair <String>
you can think the result as a class with a constructor
public Pair (String f, String s), etc . .

you can then use the instantiated generic class as it


were a normal class (almost):
Pair <String> pair = new Pair <String> ("1","2");
33

Multiple type parameters allowed

you can have multiple type parameters


class Pair <T, U> {
public T first;
public U second;
public Pair (T x, U y) { first = x; second = y; }
public Pair () { first = null; second = null; }
}

to instantiate: Pair <String, Number>

34

Which Collections do we have?


There are two main interfaces for all the collection
types in Java:
Collection<E>
Map<K,V>
List of all Collections and related frameworks:
http://java.sun.com/javase/6/docs/technotes/guides/collection
s/reference.html

35

Collection Utils
Handful Collection utils appears as static methods
of the class Collections:
http://java.sun.com/javase/6/docs/api/java/util/Collections.html

A similar set of utils for simple arrays appear in the


class Arrays:
http://java.sun.com/javase/6/docs/api/java/util/Arrays.html

36

Restrictions and limitations

in Java, generic types are compile-time entities

primitive type parameters (Pair <int>) not allowed

in C++, instantiations of a class template are compiled


separately as source code, and tailored code is produced for
each one

in C++, both classes and primitive types allowed

objects in JVM have non-generic classes:


Pair<String> strPair = new Pair<String> . .;
Pair<Number> numPair = new Pair<Number> . .;
b = strPair.getClass () == numPair.getClass ();
assert b == true; // both of the raw class Pair

but byte-code has reflective info about generics


37

Some implementations

class HashSet<E> implements Set


class TreeSet<E> implements SortedSet
class ArrayList<E> implements List
class LinkedList<E> implements List
class Vector<E> implements List

class Stack<E> extends Vector

Important methods: push, pop, peek, isEmpty

class HashMap<K, V> implements Map


class TreeMap<K, V> implements SortedMap
All of the above provide a no-argument constructor

38

The End

39

You might also like