Download as doc, pdf, or txt
Download as doc, pdf, or txt
You are on page 1of 73

Generics and Collections

Objective:-

At the end of the lesson, you should be able to:

• Explain generics concept.


• Define simple generics and subtyping with wildcard program.
• Define collections and its implementation with algorithms.
Agenda
• Introduction to Generics

• Defining simple generics

• Generics and Subtyping

• Wildcards

• Generic Methods

• Introduction to collections

• Interfaces & Implementations in Collection Framework

• Algorithms
Introduction
• Generics abstract over Types
• Classes, Interfaces and Methods can be Parameterized by Types
• Generics provide increased readability and type safety
• Generalizing Collection Classes
• Using Generics with other Java 1.5 Features
• Integration of Generics with Previous Releases
• User built generic classes
Code without Generics

• Here is a typical usage of that sort:

List myIntList = new LinkedList(); // 1


myIntList.add(new Integer(0)); // 2
Integer x = (Integer) myIntList.iterator().next(); // 3

• The most common examples are container types, such as those in the Collection hierarchy.

• The cast on line 3 is slightly annoying. Typically, the programmer knows what
kind of data has been placed into a particular list.

Note:-

• However, the cast is essential. The compiler can only guarantee that an Object will be
returned by the iterator.

• To ensure the assignment to a variable of type Integer is type safe, the cast is required.

• Of course, the cast not only introduces clutter. It also introduces the possibility of a run
time error, since the programmer might be mistaken.
Generic code
List<Integer> myIntList = new LinkedList<Integer>(); // 1’
myIntList.add(new Integer(0)); //2’
Integer x = myIntList.iterator().next(); // 3’

What if programmers could actually express their intent, and mark a list as
being restricted to contain a particular data type? This is the core idea behind generics.

Note:-

• Notice the type declaration for the variable myIntList. It specifies that this is not just an
arbitrary List, but a List of Integer, written List<Integer>.

• We say that List is a generic interface that takes a type parameter - in this case, Integer.
We also specify a type parameter when creating the list object.

• The other thing to pay attention to is that the cast is gone on line 3’. Now, you might
think that all we’ve accomplished is to move the clutter around.

• Instead of a cast to Integer on line 3, we have Integer as a type parameter on line 1’.
Defining Simple Generics
Here is a small excerpt from the definitions of the interfaces List and Iterator in package

java.util:

public interface List<E> {


void add(E x);
Iterator<E> iterator();
}
public interface Iterator<E>{
E next();
boolean hasNext();
}

Note:-

• This should all be familiar, except for the stuff in angle brackets. Those are the
declarations of the formal type parameters of the interfaces List and Iterator.

• Type parameters can be used throughout the generic declaration, pretty much where you
would use ordinary types
Defining Simple Generics

List<Integer> stands for a version of List where E has been uniformly replaced by Integer:

public interface IntegerList { void add(Integer x)


Iterator<Integer> iterator();
}

• In the introduction, we saw invocations of the generic type declaration List, such as
List<Integer>.

• In the invocation (usually called a parameterized type), all occurrences of the formal
type parameter (E in this case) are replaced by the actual type argument (in this case,
Integer).

Note:-

• This intuition can be helpful, but it’s also misleading. It is helpful, because the
parameterized type List<Integer> does indeed have methods that look just like this
expansion. It is misleading, because the declaration of a generic is never actually
expanded in this way.

• A generic type declaration is compiled once and for all, and turned into a single class file,
just like an ordinary class or interface declaration.
Defining Simple Generics

• Type parameters are analogous to the ordinary parameters used in methods or


constructors.

• Much like a method has formal value parameters that describe the kinds of values it
operates on, a generic declaration has formal type parameters.

• When a method is invoked, actual arguments are substituted for the formal
parameters, and the method body is evaluated.

Note:-

• When a generic declaration is invoked, the actual type arguments are substituted for the
formal type parameters.A note on naming conventions.

• We recommend that you use pithy (single character if possible) yet evocative names for
formal type parameters. It’s best to avoid lowercase characters in those names, making it
easy to distinguish formal type parameters from ordinary classes and interfaces.
Generics and Subtyping
List<String> ls = new ArrayList<String>(); //1
List<Object> lo = ls; //2

Line 1 is certainly legal. The trickier part is line 2.

Well, take a look at the next few lines:


lo.add(new Object()); // 3
String s = ls.get(0); // 4: attempts to assign an Object to a String!

Note:-

• Here we’ve aliased ls and lo. Accessing ls, a list of String, through the alias lo, we can
insert arbitrary objects into it.

• As a result ls does not hold just Strings anymore, and when we try and get something out
of it, we get a rude surprise.

• The Java compiler will prevent this from happening of course. Line 2 will cause a
compile time error.
• In general, if Foo is a subtype (subclass or subinterface) of Bar, and G is some generic
type declaration, it is not the case that G<Foo> is a subtype of G<Bar>.

• This is probably the hardest thing you need to learn about generics, because it goes
against our deeply held intuitions
Wildcards
//sample code 1
void printCollection(Collection c)
{
Iterator i = c.iterator();
for (k = 0; k < c.size(); k++){
System.out.println(i.next());
}}

//sample code 2

void printCollection(Collection<Object> c)
{ for (Object e : c){
System.out.println(e);
}}

Note:-

• Consider the problem of writing a routine that prints out all the elements in a collection.
Here’s how you might write it in an older version of the language: this is explained in
Sample code 1

• And here is a naive attempt at writing it using generics (and the new for loop syntax):
The problem is that this new version is much less useful than the old one.this is explained
in Sample code

• Whereas the old code could be called with any kind of collection as a parameter, the new
code only takes Collection<Object>, which, as we’ve just demonstrated, is not a
supertype of all kinds of collections!
What is the supertype of all kinds of collections?

• It’s written Collection<?> (pronounced “collection of unknown”) , that is, a collection


whose element type matches anything.

• It’s called a wildcard type for obvious reasons.

We can write:

void printCollection(Collection<?> c)
{ for (Object e : c) { System.out.println(e);
}}

and now, we can call it with any type of collection.

Note:-

• Notice that inside printCollection(), we can still read elements from c and give them type
Object. This is always safe, since whatever the actual type of the collection, it does
contain objects.It isn’t safe to add arbitrary objects to it however:
Collection<?> c = new ArrayList<String>();
c.add(new Object()); // compile time error

• Since we don’t know what the element type of c stands for, we cannot add objects to it.
The add() method takes arguments of type E, the element type of the collection.When the
actual type parameter is ?, it stands for some unknown type.

• Any parameter we pass to add would have to be a subtype of this unknown type. Since
we don’t know what type that is, we cannot pass anything in. The sole exception is null,
which is a member of every type.On the other hand, given a List<?>, we can call get()
and make use of the result..
Bounded Wildcards
Consider a simple drawing application that can draw shapes such as rectangles and
circles. To represent these shapes within the program, you could define a class hierarchy such as
this:

public abstract class Shape {


public abstract void draw(Canvas c);
}

public class Circle extends Shape {


private int x, y, radius;
public void draw(Canvas c) { ... }
}

public class Rectangle extends Shape


{ private int x, y, width, height;
public void draw(Canvas c) { ... }
}

These classes can be drawn on a canvas:

public class Canvas


{
public void draw(Shape s)
{
s.draw(this);
}
}

Any drawing will typically contain a number of shapes. Assuming that they are represented as a
list, it would be convenient to have a method in Canvas that draws them all:

public void drawAll(List<Shape> shapes)


{
for (Shape s: shapes)
{
s.draw(this);
}
}
Note:-

• Now, the type rules say that drawAll() can only be called on lists of exactly Shape: it
cannot, for instance, be called on a List<Circle>.

• That is unfortunate, since all the method does is read shapes from the list, so it could just
as well be called on aList<Circle>. What we really want is for the method to accept a list
of any kind of shape:
public void drawAll(List<? extends Shape> shapes) { ... }

• There is a small but very important difference here: we have replaced the
typeList<Shape> with List<? extends Shape>. Now drawAll() will accept lists of any
subclass of Shape, so we can now call it on a List<Circle> if we want.
List<? extends Shape> is an example of a bounded wildcard.

• The ? stands for an unknown type, just like the wildcards we saw earlier. However, in
this case, we know that this unknown type is in fact a subtype of Shape1. We say that
Shape is the upper bound of the wildcard.

• There is, as usual, a price to be paid for the flexibility of using wildcards. That price is
that it is now illegal to write into shapes in the body of the method. For instance, this is
not allowed:
public void addRectangle(List<? extends Shape> shapes)
{ shapes.add(0, new Rectangle()); // compile-time error!
}

• You should be able to figure out why the code above is disallowed. The type of the
second parameter to shapes.add() is ? extends Shape - an unknown subtype of Shape.

• Since we don’t know what type it is, we don’t know if it is a supertype of Rectangle; it
might or might not be such a supertype, so it isn’t safe to pass a Rectangle there.
• Bounded wildcards are just what one needs to handle the example of the DMV passing its
data to the census bureau.

• Our example assumes that the data is represented by mapping from names (represented as
strings) to people (represented by reference types such as Person or its subtypes, such as
Driver).

• Map<K,V> is an example of a generic type that takes two type arguments, representing
the keys and values of the map.

• Again, note the naming convention for formal type parameters - K for keys and V for
values.

public class Census


{
public static void addRegistry(Map<String, ? extends Person> registry) { ...}
}...
Map<String, Driver> allDrivers = ...;
Census.addRegistry(allDrivers);
Generic Methods
Writing a method that takes an array of objects and a collection and puts all objects in the
array into the collection.

Here is a first attempt:

static void fromArrayToCollection(Object[] a, Collection<?> c)


{
for (Object o : a)
{ c.add(o); // compile time error
}
}

By now, you will have learned to avoid the beginner’s mistake of trying to use
Collection<Object> as the type of the collection parameter.

Note:-

You may or may not have recognized that using Collection<?> isn’t going to work either.
Recall that you cannot just shove objects into a collection of unknown type.

• The way to do deal with these problems is to use generic methods.


• Just like type declarations, method declarations can be generic - that is, parameterized by
one or more type parameters.

static <T> void fromArrayToCollection(T[] a, Collection<T> c)


{
for (T o : a)
{
c.add(o); // correct
}}
We can call this method with any kind of collection whose element type is a supertype
of the element type of the array.

Object[] oa = new Object[100];


Collection<Object> co = new ArrayList<Object>();
fromArrayToCollection(oa, co); // T inferred to be Object
String[] sa = new String[100];

Collection<String> cs = new ArrayList<String>();


fromArrayToCollection(sa, cs); // T inferred to be String
fromArrayToCollection(sa, co); // T inferred to be Object
Integer[] ia = new Integer[100];
Float[] fa = new Float[100];
Number[] na = new Number[100];

Collection<Number> cn = new ArrayList<Number>();


fromArrayToCollection(ia, cn); // T inferred to be Number
fromArrayToCollection(fa, cn); // T inferred to be Number
fromArrayToCollection(na, cn); // T inferred to be Number
fromArrayToCollection(na, co); // T inferred to be Object
fromArrayToCollection(na, cs); // compile-time error

Notice that we don’t have to pass an actual type argument to a generic method. The
compiler infers the type argument for us, based on the types of the actual arguments.
It will generally infer the most specific type argument that will make the call type-correct. One
question that arises is: when should I use generic methods, and when should I use wildcard
types? To understand the answer, let’s examine a few methods from the Collection libraries.

interface Collection<E>
{ public boolean containsAll(Collection<?> c);
public boolean addAll(Collection<? extends E> c);
}

We could have used generic methods here instead:

interface Collection<E> {
public <T> boolean containsAll(Collection<T> c);
public <T extends E> boolean addAll(Collection<T> c);
// hey, type variables can have bounds too!
}

However, in both containsAll and addAll, the type parameter T is used only once. The return
type doesn’t depend on the type parameter, nor does any other argument
to the method (in this case, there simply is only one argument).

• This tells us that the type argument is being used for polymorphism; its only effect is to
allow a variety of actual argument types to be used at different invocation sites. If that is
the case, one should use wildcards. Wildcards are designed to support flexible subtyping,
which is what we’re trying to express here.

• Generic methods allow type parameters to be used to express dependencies among the
types of one or more arguments to a method and/or its return type.If there isn’t such a
dependency, a generic method should not be used.

It is possible to use both generic methods and wildcards in tandem. Here is the method
Collections.copy():

class Collections {
public static <T> void copy(List<T> dest, List<?
extends T> src){...}
}
Note the dependency between the types of the two parameters. Any object copied from the
source list, src, must be assignable to the element type T of the destination list, dst. So the
element type of src can be any subtype of T - we don’t care which.

The signature of copy expresses the dependency using a type parameter, but uses a wildcard for
the element type of the second parameter. We could have written the signature for this method
another way, without using wildcards at all:

class Collections
{
public static <T, S extends T>
void copy(List<T> dest, List<S> src){...}
}

• This is fine, but while the first type parameter is used both in the type of dst and in the
bound of the second type parameter. S, S itself is only used once, in the type of src -
nothing else depends on it. This is a sign that we can replace S with a wildcard.

• Using wildcards is clearer and more concise than declaring explicit type parameters, and
should therefore be preferred whenever possible.Wildcards also have the advantage that
they can be used outside of method signatures, as the types of fields, local variables and
arrays. Here is an example.

• Returning to our shape drawing problem, suppose we want to keep a history of drawing
requests. We can maintain the history in a static variable inside class Shape, and have
drawAll() store its incoming argument into the history field.

static List<List<? extends Shape>> history =new ArrayList<List<? extends hape>>();


public void drawAll(List<? extends Shape> shapes) {
history.addLast(shapes);
for (Shape s: shapes) {
s.draw(this);
}}

• Finally, again let’s take note of the naming convention used for the type parameters.We
use T for type, whenever there isn’t anything more specific about the type to distinguish
it. This is often the case in generic methods.

• If there are multiple type parameters, we might use letters that neighbor T in the alphabet,
such as S. If a generic method appears inside a generic class, it’s a good idea to avoid
using the same names for the type parameters of the method and class, to avoid
confusion. The same applies to nested generic classes.
What is a Collection?
• “collection” object is an object that groups multiple elements into a single unit and also
called container

• collection- which represents any of the data structures in which objects are stored and
iterated over.

• Collection - which is actually the java.util.Collection interface from which Set, List, and
Queue extend.

• Collections- which is the java.util.Collections class that holds a pile of static utility
methods for use with collections.

Note:-

• A collection — sometimes called a container — is simply an object that groups multiple


elements into a single unit. Collections are used to store, retrieve, manipulate, and
communicate aggregate data.

• collection (lowercase c), which represents any of the data structures in which objects are
stored and iterated over.

• Collection (capital C), which is actually the java.util.Collection interface


from which Set, List, and Queue extend. (That's right, extend, not implement.There are
no direct implementations of Collection.)

• Collections (capital C and ends with s) is the java.util.Collections class that holds a pile
of static utility methods for use with collections
What Do You Do with a Collection?
There are a few basic operations you'll normally use with collections:

o Add objects to the collection.

o Remove objects from the collection.

o Find out if an object (or group of objects) is in the collection.

o Retrieve an object from the collection (without removing it).

o Iterate through the collection, looking at each element (object) one after another.

What is a Collection Framework?


• A collections framework is a unified architecture for representing and manipulating
collections

• All collections frameworks contain the following:


o Interfaces
o Implementations
o Algorithms
Note:-

• Interfaces: These are abstract data types that represent collections. Interfaces allow
collections to be manipulated independently of the details of their representation. In object-
oriented languages, interfaces generally form a hierarchy.
• Implementations: Implementations are the data objects used to store collections, which
implement the interfaces. They are reusable data structures.Java Collections Framework
also provides several special-purpose implementations for situations that require
nonstandard performance, usage restrictions, or other unusual behavior
Types of Implementations
− General-purpose implementations
− Special-purpose implementations
− Concurrent implementations
− Wrapper implementations
− Convenience implementations
− Abstract implementations
• Algorithms: These are the methods that perform useful computations, such as searching
and sorting, on objects that implement collection interfaces. The algorithms are said to be
polymorphic: that is, the same method can be
Benefits of used on manyFramework
Collection different implementations of the
appropriate collection interface. In essence, algorithms are reusable functionality.
• Reduces programming effort
• Increases program speed and quality
• Allows interoperability among unrelated APIs
o The collection interfaces are the vernacular by which APIs
pass collections back and forth
• Reduce effort to learn and use new APIs
• Reduces effort to design new APIs
• Fosters software reuse
o New data structures that conform to the standard collection
interfaces are by nature reusable
Note:-

The Java Collections Framework provides the following benefits:

• Reduces programming effort: By providing useful data structures and algorithms, the
Collections Framework frees you to concentrate on the important parts of your program
rather than on the low-level "plumbing" required to make it work.
• Increases program speed and quality: This Collections Framework provides high-
performance, high-quality implementations of useful data structures and algorithms. The
various implementations of each interface are interchangeable, so programs can be easily
tuned by switching collection implementations.
• Allows interoperability among unrelated APIs: The collection interfaces are the
vernacular by which APIs pass collections back and forth. If my network administration
API furnishes a collection of node names and if your GUI toolkit expects a collection of
column headings, our APIs will interoperate seamlessly, even though they were written
independently.
• Reduces effort to learn and to use new APIs: Many APIs naturally take collections on
input and furnish them as output. In the past, each such API had a small sub-API devoted
to manipulating its collections. There was little consistency among these ad hoc
collections sub-APIs, so you had to learn each one from scratch, and it was easy to make
mistakes when using them. With the advent of standard collection interfaces, the problem
went away.
• Reduces effort to design new APIs: This is the flip side of the previous advantage.
Designers and implementers don't have to reinvent the wheel each time they create an
API that relies on collections; instead, they can use standard collection interfaces.
• Fosters software reuse: New data structures that conform to the standard collection
interfaces are by nature reusable. The same goes for new algorithms that operate on
objects that implement these interfaces.
Core Collection Interfaces

• Core collection interfaces are the foundation of the Java Collections Framework.
• Core collection interfaces form a inheritance hierarchy among themselves
o You can create a new Collection interface from them
(highly likely you don't have to)

Note:-

• Collection: the root of the collection hierarchy. A collection represents a group of


objects known as its elements. The Collection interface is the least common
denominator that all collections implement and is used to pass collections around
and to manipulate them when maximum generality is desired.
• Set: a collection that cannot contain duplicate elements. This interface models the
mathematical set abstraction and is used to represent sets.
− SortedSet: a Set that maintains its elements in ascending order.
• List: an ordered collection (sometimes called a sequence). Lists can contain duplicate
elements. The user of a List generally has precise control over where in the list each
element is inserted and can access elements by their integer index (position).

• Queue: a collection used to hold multiple elements prior to processing. Besides basic
Collection operations, a Queue provides additional insertion, extraction, and inspection
operations.

• Map: an object that maps keys to values. A Map cannot contain duplicate keys; each key
can map to at most one value.
− SortedMap: a Map that maintains its mappings in ascending key order.
“Collection” Interface (Java SE 5)
public interface Collection<E> extends Iterable<E>

{
// Basic operations
int size();
boolean isEmpty();
boolean contains(Object element);
boolean add(E element); //optional
boolean remove(Object element); //optional
Iterator<E> iterator();

Note:-

The interface does about what you'd expect given that a Collection represents a group of
objects. The interface has methods to tell you how many elements are in the collection (size,
isEmpty), to check whether a given object is in the collection (contains), to add and remove an
element from the collection (add, remove), and to provide an iterator over the collection
(iterator).
The add method is defined generally enough so that it makes sense for collections that
allow duplicates as well as those that don't. It guarantees that the Collection will contain the
specified element after the call completes, and returns true if the Collection changes as a result of
the call.
Similarly, the remove method is designed to remove a single instance of the specified
element from the Collection, assuming that it contains the element to start with, and to return true
if the Collection was modified as a result.
Two Schemes of Traversing Collections
for-each:
The for-each construct allows you to concisely traverse a collection or array using a for loop.
Syntax: for (Object o: collection)
System.out.println(o);
Iterator:
An Iterator is an object that enables you to traverse through a collection and to remove
elements from the collection selectively, if desired. You get an Iterator for a collection by
calling its iterator method. The following is the Iterator interface.
public interface Iterator<E> {
boolean hasNext();
E next();
void remove(); //optional
}
Iterate over multiple collections in parallel

Note:-

• hasNext() method returns true if the iteration has more elements.


• next() method returns the next element in the iteration.
• remove() method removes the last element that was returned by next from the underlying
Collection. It is the only safe way to modify a collection during Iteration; the behavior is
unspecified if the underlying collection is modified in any other way while the iteration is in
progress.
• Use Iterator instead of the for-each construct when you need to:
− Remove the current element. The for-each construct hides the iterator, so you cannot call
remove. Therefore, the for-each construct is not usable for filtering.
− Iterate over multiple collections in parallel.
− For Example: The for-each construct is not usable for filtering.
static void filter(Collection<?> c) {
// Bulk operations
for (Iterator<?> it = c.iterator(); it.hasNext(); )
boolean containsAll(Collection<?>
if (!cond(it.next())) c);
boolean addAll(Collection<?
it.remove(); extends E> c); //optional
boolean removeAll(Collection<?>
} c); //optional
boolean retainAll(Collection<?> c); //optional
void clear(); //optional
// Array operations
Object[] toArray();
<T> T[] toArray(T[] a);
}
Note:-

Bulk and Array Operations


• containsAll() — returns true if the target Collection contains all of the elements in the
specified Collection.
• addAll() — adds all of the elements in the specified Collection to the target Collection.
• removeAll() — removes from the target Collection all of its elements that are also contained
in the specified Collection.
• retainAll() — removes from the target Collection all its elements that are not also contained
in the specified Collection.
• clear() — removes all elements from the Collection.
• The toArray() method is provided as a bridge between collections and older APIs that expect
arrays on input.
• The array operations allow the contents of a Collection to be translated into an array.
“Set” Interface

• A collection that cannot contain duplicate elements

• Models the mathematical set abstraction and is used


to represent sets
o cards comprising a poker hand
o courses making up a student's schedule
o the processes running on a machine

• The Set interface contains only methods inherited from Collection and adds the restriction that
duplicate elements are prohibited

Notes:-

• A Set cares about uniqueness—it doesn't allow duplicates. Your good friend the equals()
method determines whether two objects are identical that is in which case only one can
be in the set.

• Sets of things May or may not be ordered and/or sorted; duplicates not allowed.
Extends Collection to handle sets, which must contain unique elements

• The Set interface defines a set. It extends Collection and declares the behavior of a
collection that does not allow duplicate elements. Therefore, the add( ) method returns
false if an attempt is made to add duplicate elements to a set. It does not define any
additional methods of its own.

“equals” operation of “Set” Interface

• Set also adds a stronger contract on the behavior of the equals and hashCode operations,
allowing Set instances to be compared meaningfully even if their implementation types
differ

− Two Set instances are equal if they contain the same elements
“Set” Interface (Java SE 5)

public interface Set<E> extends Collection<E>


{

// Basic operations
int size();
boolean isEmpty();
boolean contains(Object element);
boolean add(E element); //optional
boolean remove(Object element); //optional
Iterator<E> iterator();

Note:-

Basic operations

int size() Returns the number of elements in this collection.

boolean isEmpty() Returns true if this collection contains no elements.

boolean contains(Object o) Returns true if this collection contains the specified element.

boolean add (Object o) Ensures that this collection contains the specified element (optional
operation).

boolean remove(Object o) Removes a single instance of the specified element from this
collection, if it is present (optional operation).

Iterator iterator() Returns an iterator over the elements in this collection.

“Set” Interface (Java SE 5)


// Bulk operations

boolean containsAll(Collection<?> c);


boolean addAll(Collection<? extends E> c); //optional
boolean removeAll(Collection<?> c); //optional
boolean retainAll(Collection<?> c); //optional
void clear(); //optional

// Array Operations
Object[] toArray();
<T> T[] toArray(T[] a);
}
Notes:-

Bulk Operation & Array Operations

boolean containsAll(Collection c) Returns true if this collection contains all of the elements in
the specified collection.

boolean addAll(Collection c) Adds all of the elements in the specified collection to this
collection (optional operation).

boolean removeAll(Collection c) Removes all this collection's elements that are also contained
in the specified collection (optional operation).

boolean retainAll(Collection c) Retains only the elements in this collection that are contained in
the specified collection (optional operation).

void clear() Removes all of the elements from this collection (optional operation).

Object[] toArray() Returns an array containing all of the elements in this collection.

Object[] toArray(Object[] a) Returns an array containing all of the elements in this collection;
the runtime type of the returned array is that of the specified array.
“SortedSet” Interface

• A Set that maintains its elements in ascending order. Several additional operations are
provided to take advantage of the ordering
• Sorted sets are used for naturally ordered sets, such as word lists and membership roll
• The SortedSet interface provides operations for the following:
− Range view: allows arbitrary range operations on the sorted set .
− Endpoints: return the first or last element in the sorted set.
− Comparator access: returns the Comparator, if any, used to sort the set.

Note:-

A SortedSet is a Set that maintains its elements in ascending order, sorted according to the
elements' natural ordering or according to a Comparator provided at SortedSet creation time.

The operations that SortedSet inherits from Set behave identically on sorted sets and normal sets
with two exceptions:
− The Iterator returned by the iterator operation traverses the sorted set in order.
− The array returned by toArray contains the sorted set's elements in order.

Although the interface doesn't guarantee it, the toString method of the Java platform's SortedSet
implementations returns a string containing all the elements of the sorted set, in order.

SortedSet implementations also provide, by convention, a constructor that takes a Comparator


and returns an empty set sorted according to the specified Comparator. If null is passed to this
constructor, it returns a set that sorts its elements according to their natural ordering.
“Set” Interface
public interface SortedSet<E> extends Set<E> {
// Range-view
SortedSet<E> subSet(E fromElement, E toElement);
SortedSet<E> headSet(E toElement);
SortedSet<E> tailSet(E fromElement);

// Endpoints
E first();
E last();

// Comparator access
Comparator<? super E> comparator();
}

Note:-

Range-view Operations
The range-view operations are somewhat analogous to those provided by the List interface, but
there is one big difference. Range views of a sorted set remain valid even if the backing sorted
set is modified directly. Sorted sets provide three range-view operations.
subSet, takes two endpoints, Like subList. The range is half open, including its low endpoint but
excluding the high one.
headSet and tailSet, both of which take a single Object argument. The former returns a view of
the initial portion of the backing SortedSet, up to but not including the specified object.
Endpoint Operations
The SortedSet interface contains operations to return the first and last elements in the sorted set,
not surprisingly called first and last.
Comparator Accessor
The SortedSet interface contains an accessor method called comparator that returns the
Comparator used to sort the set, or null if the set is sorted according to the natural ordering of its
elements. This method is provided so that sorted sets can be copied into new sorted sets with the
same ordering.
Implementations of “Set” Interface
General-Purpose Set Implementations

• HashSet: No ordering guarantees


• TreeSet: Order according to values.

• LinkedHashSet: Order according to insertion

Special-Purpose Set Implementations


• EnumSet: A set implementation for enum types
• CopyOnWriteArraySet: A set implementation backed up by a copy-on-write array

Note:-
• HashSet is much faster than TreeSet (constant-time versus log-time for most operations)
but offers no ordering guarantees.
• If you need to use the operations in the SortedSet interface, or if value-ordered iteration is
required, use TreeSet; otherwise, use HashSet. It's a fair bet that you'll end up using
HashSet most of the time.
• LinkedHashSet is in some sense intermediate between HashSet and TreeSet.
Implemented as a hash table with a linked list running through it, it provides insertion-
ordered iteration (least recently inserted to most recently) and runs nearly as fast as
HashSet.
• EnumSet is a high-performance Set implementation for enum types. All of the members
of an enum set must be of the same enum type. Internally, it is represented by a bit-
vector, typically a single long. Enum sets support iteration over ranges of enum types.
• CopyOnWriteArraySet is a Set implementation backed up by a copy-on-write array. All
mutative operations, such as add, set, and remove, are implemented by making a new
copy of the array; no locking is ever required. Even iteration may safely proceed
concurrently with element insertion and deletion.
HashSet Constructors
Constructors

HashSet(int initialCapacity, float loadFactor)


HashSet(int initialCapacity)
HashSet()
HashSet(Collection<? extends E> c)

HashSet : Implements Set Interface.

The elements are not stored in sorted order.

HashSet hs=new HashSet( );


hs.add(“m”);

Notes:-

This class implements the Set interface, backed by a hash table (actually a HashMap instance). It
makes no guarantees as to the iteration order of the set; in particular, it does not guarantee that
the order will remain constant over time. This class permits the null element.

This class offers constant time performance for the basic operations (add, remove, contains and
size), assuming the hash function disperses the elements properly among the buckets.

Iterating over this set requires time proportional to the sum of the HashSet instance's size (the
number of elements) plus the "capacity" of the backing HashMap instance (the number of
buckets). Thus, it's very important not to set the initial capacity too high (or the load factor too
low) if iteration performance is important.

Iteration is linear in the sum of the number of entries and the number of buckets (the capacity)

• Choosing an initial capacity that's too high can waste both space and time
• Choosing an initial capacity that's too low wastes time by copying the data structure each
time it's forced to increase its capacity
Example: Set Interface & HashSet

public class MyOwnUtilityClass {

//**Note that the first parameter type is set to Set interface not a particular implementation
class such as HashSet. This makes the caller of this method to pass instances of different
implementations of Set interface while this function picks up polymorphic behavior
depending on the actual implementation type of the object instance passed.*/

public static void checkDuplicate(Set s, String[] args)


{
for (int i=0; i<args.length; i++)
if (!s.add(args[i]))
System.out.println("Duplicate detected: "+args[i]);
System.out.println(s.size()+" distinct words detected: "+s);
}
}

Example: Set Interface & HashSet

public class Main


{
public static void main(String[] args)
{
Set s = new HashSet(); // Order is not guaranteed
MyOwnUtilityClass.checkDuplicate(s, args);
s = new TreeSet(); // Order according to values
MyOwnUtilityClass.checkDuplicate(s, args);
s = new LinkedHashSet(); // Order according to insertion
MyOwnUtilityClass.checkDuplicate(s, args);
}
}

Output :

The numbers are added in the following order


23412
Set type = java.util.HashSet [3, 2, 4, 1]
Set type = java.util.TreeSet [1, 2, 3, 4]
Set type = java.util.LinkedHashSet [2, 3, 4, 1]
TreeSet Constructors

Constructors
TreeSet(Collection<? extends E> c)
TreeSet()
TreeSet(Comparator<? super E> comparator)
TreeSet (SortedSet<E> s)

Note:-

• This implementation provides guaranteed log(n) time cost for the basic operations (add,
remove and contains).

• Note that the ordering maintained by a set (whether or not an explicit comparator is
provided) must be consistent with equals if it is to correctly implement the Set interface.
(See Comparable or Comparator for a precise definition of consistent with equals.)

• This is so because the Set interface is defined in terms of the equals operation, but a
TreeSet instance performs all element comparisons using its compareTo (or compare)
method, so two elements that are deemed equal by this method are, from the standpoint
of the set, equal.

• The behavior of a set is well-defined even if its ordering is inconsistent with equals; it
just fails to obey the general contract of the Set interface.
Example: Set Interface & TreeSet

Class SampleTreeSet{
public static void main(String[] args) {
Set ts = new TreeSet();
ts.add("one");
ts.add("two");
ts.add("three");
ts.add("four");
ts.add("three");
System.out.println("Members from TreeSet = " + ts);
}
}

Output:
Members from TreeSet = [four, one, three, two]
TreeSet Constructors

Constructors
LinkedHashSet()
LinkedHashSet (Collection<? extends E> c)
LinkedHashSet (int initialCapacity, float loadFactor)
LinkedHashSet (int initialCapacity)

Note:-
• Hash table and linked list implementation of the Set interface, with predictable iteration
order. This implementation differs from HashSet in that it maintains a doubly-linked list
running through all of its entries.
• This linked list defines the iteration ordering, which is the order in which elements were
inserted into the set (insertion-order).
• This class provides all of the optional Set operations, and permits null elements. Like
HashSet, it provides constant-time performance for the basic operations (add, contains
and remove),
• A linked hash set has two parameters that affect its performance: initial capacity and
load factor. They are defined precisely as for HashSet.
Example: Set Interface & LinkedHashSet

Class SampleLinkedHashSet{
public static void main(String[] args)
{
Set ts2 = new LinkedHashSet();
ts2.add(2);
ts2.add(1);
ts2.add(3);
ts2.add(3);
System.out.println("Members from LinkedHashSet = " + ts2);
}
}

Output:
Members from LinkedHashSet = [2, 1, 3]
“List” Interface

• An ordered collection (sometimes called a sequence)


• Lists can contain duplicate elements
• The user of a List generally has precise control over where in the list each element is
inserted and can access elements by their integer index (position)

− If you've used Vector, you're already familiar with the general basics of List

Note:-

List extends Collection Interface. The classes Array List, Vector List & Linked List implements
List Interface.

• Represents the sequence of numbers in a fixed order.


• But may contain duplicate elements.
• Elements can be inserted or retrieved by their position in the List using Zero based index.
• List stores elements in an ordered way.
Additional Operations Supported by “List” Interface over
“Collection”

public interface List<E> extends Collection<E>


{
// Positional access
// Search
// Iteration
// Range-view
}

Note:-

• Positional access — manipulates elements based on their numerical position in the list

• Search — searches for a specified object in the list and returns its numerical position

• Iteration — extends Iterator semantics to take advantage of the list's sequential nature

• Range-view — performs arbitrary range operations on the list.


“List” Interface

public interface List<E> extends Collection<E>


{
// Positional access
E get(int index);
E set(int index, E element); //optional
boolean add(E element); //optional
void add(int index, E element); //optional
E remove(int index); //optional
boolean addAll(int index, Collection<? extends E> c); //optional
// Search
// Iteration
// Range-view
}

Note:-

public E get(int index) Returns the element at the specified position in this list.

public E set(int index,E element) Replaces the element at the specified position in this list with
the specified element (optional operation).
public boolean add(E e) Appends the specified element to the end of this list (optional
operation).
public void add(int index,E element) Inserts the specified element at the specified position in
this list (optional operation). Shifts the element currently at that position (if any) and any
subsequent elements to the right (adds one to their indices).
public E remove(int index) Removes the element at the specified position in this list (optional
operation).
public boolean addAll(int index,Collection c) Inserts all of the elements in the specified
collection into this list at the specified position (optional operation).
“List” Interface

public interface List<E> extends Collection<E>


{

// Positional access
// Search
int indexOf(Object o);
int lastIndexOf(Object o);

// Iteration
ListIterator<E> listIterator();
ListIterator<E> listIterator(int index);

// Range-view
List<E> subList(int from, int to);

Note:-

public int indexOf(Object o) Returns the index in this list of the first occurrence of the
specified element, or -1 if this list does not contain this element. More formally, returns the
lowest index i such that (o==null ? get(i)==null : o.equals(get(i))), or -1 if there is no such index.
public int lastIndexOf(Object o)Returns the index in this list of the last occurrence of the
specified element, or -1 if this list does not contain this element. More formally, returns the
highest index i such that (o==null ? get(i)==null : o.equals(get(i))), or -1 if there is no such
index.

// Iteration

public ListIterator listIterator() Returns a list iterator of the elements in this list (in proper
sequence).
public ListIterator listIterator(int index) Returns a list iterator of the elements in this list (in
proper sequence), starting at the specified position in this list. The specified index indicates the
first element that would be returned by an initial call to the next method. An initial call to the
previous method would return the element with the specified index minus one.
// Range-view

public List subList(int fromIndex, int toIndex) Returns a view of the portion of this list
between the specified fromIndex, inclusive, and toIndex, exclusive. (If fromIndex and toIndex
are equal, the returned list is empty.) The returned list is backed by this list, so non-structural
changes in the returned list are reflected in this list, and vice-versa. The returned list supports all
of the optional list operations supported by this list.
Implementations of “List” Interface

ArrayList :
• Implements List Interface.
• Array can dynamically increase or decrease size.
• Array List are ment for Random ascessing.
• Array List are created with intial size, when the size is increased, the collection is
automatically enlarged. When an Objects are removed, the array may be shrunk.
Syntax:
ArrayList a1=new ArrayList( );
A1.add(“a”);

Note:-

• Resizable-array implementation of the List interface. Implements all optional list


operations, and permits all elements, including null. In addition to implementing the List
interface, this class provides methods to manipulate the size of the array that is used
internally to store the list. (This class is roughly equivalent to Vector, except that it is
unsynchronized.)

• The size, isEmpty, get, set, iterator, and listIterator operations run in constant time. The
add operation runs in amortized constant time, that is, adding n elements requires O(n)
time. All of the other operations run in linear time (roughly speaking). The constant
factor is low compared to that for the LinkedList implementation.

• Each ArrayList instance has a capacity. The capacity is the size of the array used to store
the elements in the list. It is always at least as large as the list size. As elements are added
to an ArrayList, its capacity grows automatically. The details of the growth policy are not
specified beyond the fact that adding an element has constant amortized time cost.
Implementations of “List” Interface

• Linked List : Implements List Interface.


• Inserting or removing elements in the middle of the array.
• Linked list are meant for Sequential accessing.
• Stores Objects in a separate link.

− Use it you frequently add elements to the beginning of the List or iterate over the List to delete
elements from its interior

Syntax:

LinkedList l1=new LinkedList( );


l1.add(“R”);

Note:-

• Linked list implementation of the List interface. Implements all optional list operations,
and permits all elements (including null). In addition to implementing the List interface,
the LinkedList class provides uniformly named methods to get, remove and insert an
element at the beginning and end of the list. These operations allow linked lists to be used
as a stack, queue, or double-ended queue (deque).
• All of the stack/queue/deque operations could be easily recast in terms of the standard list
operations. They're included here primarily for convenience, though they may run
slightly faster than the equivalent List operations.
• All of the operations perform as could be expected for a doubly-linked list. Operations
that index into the list will traverse the list from the begining or the end, whichever is
closer to the specified index.
// Demonstrate ArrayList.

import java.util.*;
class ArrayListDemo {
public static void main(String args[]) {
// create an array list
ArrayList al = new ArrayList();
System.out.println("Initial size of al: " +
al.size());
// add elements to the array list
al.add("C");
al.add("A");
al.add("E");
al.add("B");
al.add("D");
al.add("F");
al.add(1, "A2");
System.out.println("Size of al after additions: " +
al.size());
// display the array list
System.out.println("Contents of al: " + al);
// Remove elements from the array list
al.remove("F");
al.remove(2);
System.out.println("Size of al after deletions: " +
al.size());
System.out.println("Contents of al: " + al);
}
}

The output from this program is shown here:

Initial size of al: 0


Size of al after additions: 7
Contents of al: [C, A2, A, E, B, D, F]
Size of al after deletions: 5
Contents of al: [C, A2, E, B, D]
The following program illustrates several of the methods supported by LinkedList:
// Demonstrate LinkedList.
import java.util.*;
class LinkedListDemo {
public static void main(String args[]) {
// create a linked list
LinkedList ll = new LinkedList();
// add elements to the linked list
ll.add("F");
ll.add("B");
ll.add("D");
ll.add("E");
ll.add("C");
ll.addLast("Z");
ll.addFirst("A");
ll.add(1, "A2");
E JAVA LIBRARY
System.out.println("Original contents of ll: " + ll);
// remove elements from the linked list
ll.remove("F");
ll.remove(2);
System.out.println("Contents of ll after deletion: "
+ ll);
// remove first and last elements
ll.removeFirst();
ll.removeLast();
System.out.println("ll after deleting first and last: "
+ ll);
// get and set a value
Object val = ll.get(2);
ll.set(2, (String) val + " Changed");
System.out.println("ll after change: " + ll);
}
}

The output from this program is“Map” Interface


shown here:

Original contents of ll: [A, A2, F, B, D, E, C, Z]


Contents
• MapofInterface:
ll after deletion: [A, A2, D,
Basic Interface. E, classes
The C, Z] Hash Map & HashTable implements Map
ll after deleting first and last: [A2, D, E, C]
interface.
ll after change: [A2, D, E Changed, C]
• Handles key/value pairs
− Used to represent the mapping of unique keys to values.
− By using the key value we can retrive the values.
− Two basic operations are get( ) & put( ) .
boolean put(Object key, Object value) : Inserts given value into map with key
Object get(Object key) : Reads value for the given key
.

Note:-

• An object that maps keys to values. A map cannot contain duplicate keys; each key can
map to at most one value.
• This interface takes the place of the Dictionary class, which was a totally abstract class
rather than an interface.
• The Map interface provides three collection views, which allow a map's contents to be
viewed as a set of keys, collection of values, or set of key-value mappings. The order of a
map is defined as the order in which the iterators on the map's collection views return
their elements. Some map implementations, like the TreeMap class, make specific
guarantees as to their order; others, like the HashMap class, do not.

“Map” Interface (Java SE 5)


public interface Map<K,V>
{
// Basic operations
V put(K key, V value);
V get(Object key);
V remove(Object key);
boolean containsKey(Object key);
boolean containsValue(Object value);
int size();
boolean isEmpty();
Note:-
Basic operations
public Object put(Object key, Object value) Associates the specified value with the specified
key in this map (optional operation). If the map previously contained a mapping for this key, the
old value is replaced by the specified value. (A map m is said to contain a mapping for a key k if
and only if m.containsKey(k) would return true.))

public Object get(Object key) Returns the value to which this map maps the specified key.
Returns null if the map contains no mapping for this key. A return value of null does not
necessarily indicate that the map contains no mapping for the key; it's also possible that the map
explicitly maps the key to null. The containsKey operation may be used to distinguish these two
cases.

public Object remove(Object key) Removes the mapping for this key from this map if it is
present (optional operation). More formally, if this map contains a mapping from key k to value
v such that (key==null ? k==null : key.equals(k)), that mapping is removed. (The map can
contain at most one such mapping.)

public boolean containsKey(Object key) Returns true if this map contains a mapping for the
specified key. More formally, returns true if and only if this map contains at a mapping for a key
k such that (key==null ? k==null : key.equals(k)). (There can be at most one such mapping.)
public boolean containsValue(Object value) Returns true if this map maps one or more keys to
the specified value. More formally, returns true if and only if this map contains at least one
mapping to a value v such that (value==null ? v==null : value.equals(v)). This operation will
probably require time linear in the map size for most implementations of the Map interface.

public int size() Returns the number of key-value mappings in this map. If the map contains
Map” Interface (Java SE 5)
re than Integer.MAX_VALUE elements, returns Integer.MAX_VALUE.
// Bulkboolean
public operations
isEmpty()
void putAll(Map<? extends
Returns true if this map K, ?no
contains extends V> m);
key-value mappings.
void clear();

// Collection Views
public Set<K> keySet();
public Collection<V> values();
public Set<Map.Entry<K,V>> entrySet();

Note:-
Bulk operations
public void putAll(Map t) Copies all of the mappings from the specified map to this map
(optional operation). The effect of this call is equivalent to that of calling put(k, v) on this map
once for each mapping from key k to value v in the specified map. The behavior of this operation
is unspecified if the specified map is modified while the operation is in progress.

public void clear()


Removes all mappings from this map (optional operation).

Collection Views
public Set keySet() Returns a set view of the keys contained in this map. The set is backed by
the map, so changes to the map are reflected in the set, and vice-versa. If the map is modified
while an iteration over the set is in progress, the results of the iteration are undefined. The set
supports element removal, which removes the corresponding mapping from the map, via the
Iterator.remove, Set.remove, removeAll retainAll, and clear operations. It does not support the
add or addAll operations.
public Collection values() Returns a collection view of the values contained in this map. The
collection is backed by the map, so changes to the map are reflected in the collection, and vice-
versa. If the map is modified while an iteration over the collection is in progress, the results of
the iteration are undefined. The collection supports element removal, which removes the
corresponding mapping from the map, via the Iterator.remove, Collection.remove, removeAll,
retainAll and clear operations. It does not support the add or addAll operations.

public Set entrySet() Returns a set view of the mappings contained in this map. Each element
in the returned set is a Map.Entry. The set is backed by the map, so changes to the map are
reflected in the set, and vice-versa. If the map is modified while an iteration over the set is in
progress, the results of the iteration are undefined. The set supports element removal, which
removes the corresponding mapping from the map, via the Iterator.remove, Set.remove,
removeAll, retainAll and clear operations. It does not support the add or addAll operations.
Map” Interface (Java SE 5)
// Interface for entrySet elements
public interface Entry {
K getKey();
V getValue();
V setValue(V value);
}

Note:-

Interface for entrySet elements

public Object getKey() Returns the key corresponding to this entry.

public Object getValue() Returns the value corresponding to this entry. If the mapping has been
removed from the backing map (by the iterator's remove operation), the results of this call are
undefined.

public Object setValue(Object value) Replaces the value corresponding to this entry with the
specified value (optional operation). (Writes through to the map.) The behavior of this call is
undefined if the mapping has already been removed from the map (by the iterator's remove
operation).
“SortedMap” Interface
• A Map that maintains its mappings in ascending key order
− This is the Map analog of SortedSet
• Sorted maps are used for naturally ordered collections of key/value pairs, such as dictionaries
and telephone directories

Sorted Map : extends Map Interface.


− The Class Tree Map implements Sorted Map Interface.
− Maintain the values of key order.
− The entries are maintained in ascending order.

Note:-

• A map that further guarantees that it will be in ascending key order, sorted according to
the natural ordering of its keys (see the Comparable interface), or by a comparator
provided at sorted map creation time.
• This order is reflected when iterating over the sorted map's collection views (returned by
the entrySet, keySet and values methods). Several additional operations are provided to
take advantage of the ordering. (This interface is the map analogue of the SortedSet
interface.)
• All keys inserted into a sorted map must implement the Comparable interface (or be
accepted by the specified comparator). Furthermore, all such keys must be mutually
comparable: k1.compareTo(k2) (or comparator.compare(k1, k2)) must not throw a
ClassCastException for any elements k1 and k2 in the sorted map. Attempts to violate
this restriction will cause the offending method or constructor invocation to throw a
ClassCastException.
• Note that the ordering maintained by a sorted map (whether or not an explicit comparator
is provided) must be consistent with equals if the sorted map is to correctly implement
the Map interface. (See the Comparable interface or Comparator interface for a precise
definition of consistent with equals.)
Implementations of “Map” Interface
HashMap
• hashes the keys
• The Elements may not in Order.
• Hash Map is not synchronized and permits null values
• Hash Map is not serialized.
• Hash Map supports Iterators.
The following constructors are defined:
HashMap( )
HashMap(Map m)
HashMap(int capacity)
HashMap(int capacity, float fillRatio)

Note:-
• Use it you want maximum speed and don't care about iteration order Most commonly
used implementation
• 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
Implementations of “Map” Interface

• LinkedHashMap
− Use if you want near-HashMap performance and insertion order Iteration
• This class extends HashMap.
• It maintains a linked list of the entries in the map, in the order in which they were inserted.
• This allows insertion-order iteration over the map.
LinkedHashMap defines the following constructors.
LinkedHashMap( )
LinkedHashMap(Map m)
LinkedHashMap(int capacity)
LinkedHashMap(int capacity, float fillRatio)
LinkedHashMap(int capacity, float fillRatio, boolean Order)

Note:-

• That is, when iterating a LinkedHashMap, the elements will be returned in the order in
which they were inserted.
• You can also create a LinkedHashMap that returns its elements in the order in which
they were last accessed.
• The first form constructs a default LinkedHashMap.
• The second form initializes the LinkedHashMap with the elements from m.
• The third form initializes the capacity.
• The fourth form initializes both capacity and fill ratio. The meaning of capacity and fill
ratio are the same as for HashMap.
• The last form allows you to specify whether the elements will be stored in the linked list
by insertion order, or by order of last access. If Order is true, then access order is used. If
Order is false, then insertion order is used.
Implementations of “Map” Interface
• TreeMap :Implements Sorted Set Interface.
− The elements are stored in sorted ascending order.
− Using key value we can retrieve the data.
Syntax:-
TreeMap tm=new TreeMap( );
tm.put( “Prasad”,new Double(74.6));

The following TreeMap constructors are defined:


TreeMap( )
TreeMap(Comparator comp)
TreeMap(Map m)
TreeMap(SortedMap sm)

Note:-

Provides an efficient means of storing key/value pairs in sorted order and allows rapid retrivals.

• The first form constructs an empty tree map that will be sorted by using the natural order
of its keys.
• The second form constructs an empty tree-based map that will be sorted by
using the Comparator comp. (Comparators are discussed later in this chapter.)
• The third form initializes a tree map with the entries from m, which will be sorted by
using thenatural order of the keys.
• The fourth form initializes a tree map with the entries from sm, which will be sorted in
the same order as sm.
//HashMap Demo
import java.util.*;
class HashMapDemo
{
public static void main(String args[]) {
// Create a hash map
HashMap hm = new HashMap();
// Put elements to the map
hm.put("John Doe", new Double(3434.34));
hm.put("Tom Smith", new Double(123.22));
hm.put("Jane Baker", new Double(1378.00));
hm.put("Todd Hall", new Double(99.22));
hm.put("Ralph Smith", new Double(-19.08));
// Get a set of the entries
Set set = hm.entrySet();
// Get an iterator
Iterator i = set.iterator();
// Display elements
while(i.hasNext()) {
Map.Entry me = (Map.Entry)i.next();
System.out.print(me.getKey() + ": ");
System.out.println(me.getValue());
}
System.out.println();
// Deposit 1000 into John Doe's account
double balance = ((Double)hm.get("John Doe")).doubleValue();
hm.put("John Doe", new Double(balance + 1000));
System.out.println("John Doe's new balance: " +
hm.get("John Doe"));
}
}

Output from this program is shown here (the precise order may vary).
Todd Hall: 99.22
Ralph Smith: -19.08
John Doe: 3434.34
Jane Baker: 1378.0
Tom Smith: 123.22
John Doe’s current balance: 4434.34
//TreeMapDemo

import java.util.*;
class TreeMapDemo {
public static void main(String args[]) {
// Create a tree map
TreeMap tm = new TreeMap();
// Put elements to the map
tm.put("John Doe", new Double(3434.34));
tm.put("Tom Smith", new Double(123.22));
tm.put("Jane Baker", new Double(1378.00));
tm.put("Todd Hall", new Double(99.22));
tm.put("Ralph Smith", new Double(-19.08));
// Get a set of the entries
Set set = tm.entrySet();
// Get an iterator
Iterator i = set.iterator();
// Display elements
while(i.hasNext()) {
Map.Entry me = (Map.Entry)i.next();
System.out.print(me.getKey() + ": ");
System.out.println(me.getValue());
}
System.out.println();
// Deposit 1000 into John Doe's account
double balance = ((Double)tm.get("John Doe")).doubleValue();
tm.put("John Doe", new Double(balance + 1000));
System.out.println("John Doe's new balance: " +
tm.get("John Doe"));
}
}

The following is the output from this program:


Jane Baker: 1378.0
John Doe: 3434.34
Ralph Smith: -19.08
Todd Hall: 99.22
Tom Smith: 123.22
John Doe’s current balance: 4434.34
“Queue” Interface

• A collection used to hold multiple elements prior to processing

• Besides basic Collection operations, a Queue provides additional insertion, extraction, and
inspection operations

• Typically, but do not necessarily, order elements in a FIFO (first-in, first-out) manner

Note:-

• A collection designed for holding elements prior to processing. Besides basic


Collection operations, queues provide additional insertion, extraction, and inspection
operations.
• Queues typically, but do not necessarily, order elements in a FIFO (first-in-first-out)
manner.
• Among the exceptions are priority queues, which order elements according to a supplied
comparator, or the elements' natural ordering, and LIFO queues (or stacks) which order
the elements LIFO (last-in-first-out).
• Whatever the ordering used, the head of the queue is that element which would be
removed by a call to remove() or poll(). In a FIFO queue, all new elements are inserted
at the tail of the queue. Other kinds of queues may use different placement rules. Every
Queue implementation must specify its ordering properties.
Implementations of Queue Interface

• General purpose Queue implementations

− LinkedList implements the Queue interface, providing FIFO queue operations for add,
poll, and so on

− PriorityQueue class is a priority queue based on the heap data structure

− This queue orders elements according to an order specified at construction time, which can
be the elements' natural ordering or the ordering imposed by an explicit Comparator.

• Concurrent Queue implementations

Note:-

• The PriorityQueue class is a priority queue based on the heap data structure. This queue
orders elements according to an order specified at construction time, which can be the
elements' natural ordering or the ordering imposed by an explicit Comparator.

• The queue retrieval operations — poll, remove, peek, and element — access the element
at the head of the queue. The head of the queue is the least element with respect to the
specified ordering. If multiple elements are tied for least value, the head is one of those
elements; ties are broken arbitrarily.

• PriorityQueue and its iterator implement all of the optional methods of the Collection and
Iterator interfaces. The iterator provided in method iterator is not guaranteed to traverse
the elements of the PriorityQueue in any particular order. If you need ordered traversal,
consider using Arrays.sort(pq.toArray()).
Algorithms

• Provided as static methods of Collections class


• The first argument is the collection on which the operation is to be performed
• The majority of the algorithms provided by the Java platform operate on List instances, but
a few of them operate on arbitrary Collection instances

This section briefly describes the following algorithms


− Sorting
− Shuffling
− Routine data manipulation
− Searching
− Composition
− Find extreme values

Note:-
• The polymorphic algorithms described here are pieces of reusable functionality provided
by the Java platform.

• All of them come from the Collections class, and all take the form of static methods
whose first argument is the collection on which the operation is to be performed.

• The great majority of the algorithms provided by the Java platform operate on List
instances, but a few of them operate on arbitrary Collection instances.
Sorting
• The sort algorithm reorders a List so that its elements are in ascending order according to an
ordering relationship

• Two forms of the operations

− takes a List and sorts it according to its elements' natura ordering


− takes a Comparator in addition to a List and sorts the elements with the Comparator

Note:-

Sort by Natural Ordering


• The type of the elements in a List already implements Comparable interface
Examples
− If the List consists of String elements, it will be sorted into alphabetical order
− If it consists of Date elements, it will be sorted into chronological order
− String and Date both implement the Comparable interface.
− Comparable implementations provide a natural ordering for a class,
which allows objects of that class to be sorted automatically
• If you try to sort a list, the elements of which do not implement Comparable,
Collections.sort(list) will throw a ClassCastException.

Sorting by Comparator Interface

− A comparison function, which imposes a total ordering on some collection of


objects.

− Comparators can be passed to a sort method (such as Collections.sort or


Arrays.sort) to allow precise control over the sort order

− Comparators can also be used to control the order of certain data structures (such
as sorted sets or sorted maps), or to provide an ordering for collections of objects
that don't have a natural ordering
Sorting by Natural Order of List
// Set up test data
String n[] = {
new String("John"),
new String("Karl"),
new String("Groucho"),
new String("Oscar")
};

// Create a List from an array


List l = Arrays.asList(n);
// Perform the sorting operation
Collections.sort(l);

Sorting by Natural Order of List


// Set up test data

ArrayList u2 = new ArrayList();


u2.add("Beautiful Day");
u2.add("Stuck In A Moment You Can't Get Out Of");
u2.add("Elevation");
u2.add("Walk On");
u2.add("Kite");
u2.add("In A Little While");
u2.add("Wild Honey");
u2.add("Peace On Earth");
u2.add("When I Look At The World");
u2.add("New York");
u2.add("Grace");
Comparator comp = Comparators.stringComparator();
Collections.sort(u2, comp);
System.out.println(u2);
Shuffling

• The shuffle algorithm does the opposite of what sort does, destroying any trace of order that
may have been present in a List
− That is, this algorithm reorders the List based on input from a source of randomness
such that all possible permutations occur with equal likelihood, assuming a fair source
of randomness
• Useful in implementing games of chance
− could be used to shuffle a List of Card objects representing a deck
− generating test cases
Routine Data Manipulation

The Collections class provides five algorithms for doing routine data manipulation
on List Objects

− reverse
− fill
− copy
− swap
− addall

Note:-

• reverse — reverses the order of the elements in a List.

• fill — overwrites every element in a List with the specified value. This operation is useful
for reinitializing a List.

• copy — takes two arguments, a destination List and a source List, and copies the
elements of the source into the destination, overwriting its contents. The destination List
must be at least as long as the source. If it is longer, the remaining elements in the
destination List are unaffected.

Searching
• swap — swaps the elements at the specified positions in a List.

The binarySearch algorithm searches for a specified element in a sorted List. This algorithm has
two•forms.
addAll — adds all the specified elements to a Collection. The elements to be added may
be specified individually or as an array.
// Set up testing data
String name[] = {
new String("Sang"),
new String("Shin"),
new String("Boston"),
new String("Passion"),
new String("Shin"),
};

List l = Arrays.asList(name);
int position = Collections.binarySearch(l, "Boston");
System.out.println("Position of the searched item = " + position);
Note:-

• The first takes a List and an element to search for (the "search key"). This form assumes
that the List is sorted in ascending order according to the natural ordering of its
elements.

• The second form takes a Comparator in addition to the List and the search key, and
assumes that the List is sorted into ascending order according to the specified
Comparator. The sort algorithm can be used to sort the List prior to calling
binarySearch.
Composition
• The return value is the same for both forms. If the List contains the search key, its index
Collections.frequency(l)
is returned. If not, the return value is (-(insertion point) - 1), where the insertion
point is the point at which the value would be inserted into the List, or the index of the
Counts the number of times the specified element occurs in the specified collection.
first element greater than the value or list.size() if all elements in the List are less
than the specified value.
Collections.disjoint(l1, l2)

Determines whether two Collections are disjoint; that is, whether they contain no elements
in commonThe Collections class has binarySearch() method for searching a specified element in
a sorted List
// Demonstrate various algorithms.
import java.util.*;
class AlgorithmsDemo {
public static void main(String args[]) {
// Create and initialize linked list
LinkedList ll = new LinkedList();
ll.add(new Integer(-8));
ll.add(new Integer(20));
ll.add(new Integer(-20));
ll.add(new Integer(8));
// Create a reverse order comparator
Comparator r = Collections.reverseOrder();
// Sort list by using the comparator
Collections.sort(ll, r);
// Get iterator
Iterator li = ll.iterator();
System.out.print("List sorted in reverse: ");
while(li.hasNext())
System.out.print(li.next() + " ");
System.out.println();
Collections.shuffle(ll);
// display randomized list
li = ll.iterator();
System.out.print("List shuffled: ");
while(li.hasNext())
System.out.print(li.next() + " ");
System.out.println();
System.out.println("Minimum: " + Collections.min(ll));
System.out.println("Maximum: " + Collections.max(ll));
}
}

Output from this program is shown here:

List sorted in reverse: 20 8 -8 -20


List shuffled: 20 -20 8 -8
Minimum: -20
Maximum: 20

Notice that min( ) and max( ) operate on the list after it has been shuffled. Neither
requires a sorted list for its operation.

You might also like