Saturday, 3 August 2013

38:Threads

Learning Objectives
After completing this session, you will be able to:
‰  Define a thread
‰  Identify the thread priorities
Threads
‰  Threads are required to handle concurrent processes.
‰  Definition of threads:Single sequential flow of control within a program
‰  For simplicity, think of threads asprocesses executed by a program
‰  Example:
oOperating System
oHotJava Web browser
The following diagram shows sequential program and multi-threaded program:
Multi-Threading in Java Platform
‰  Every application has at least one thread or several, if you count "system" threads that
do things like memory management and signal handling.
‰  But from the point of view of application programmer, you start with just one thread,
called the main thread. This thread has the ability to create additional threads.
Thread Priorities
‰  Priorities determine, which thread receives CPU control and gets to be executed first.
‰  Definition: Integer value ranging from one to 10
‰  Higher the thread priority larger isthe chance of being executed first
‰  Example:
Two threads are ready to run
First thread: priority of 5, already running
Second thread = priority of 10, comes in while first thread is running
‰  Context switch:Occurs when a thread snatches the control of CPU from another
‰  When does it occur?
oRunning thread voluntarily relinquishes CPU control
oRunning thread is preempted by a higher priority thread
‰  There might occur some situations that more than one highest priority threads are
ready to run.
‰  The decision that which of the highest priority threads receives the CPU control is
dependent on the operating system.
‰  Windows 95/98/NT:Uses time-sliced round-robin
‰  Solaris:Executing thread should voluntarily relinquish CPU control
Try It Out
Problem Statement:
Write a program that illustrates the construction of threads and starting the threads.
Code:
class ThreadPriorityApp {
public static void main(String args[]) {
MyThread t1 = new MyThread("t1");
MyThread t2 = new MyThread("t2");
t1.start();
t2.start();
}
}
class MyThread extends Thread {
public void displayOutput(String s) {
System.out.println(s);
}
How It Works:
When you run the program,the output sequence will vary fromcomputer to computer. Also, the
output differs between each and every run.
After first time executionAfter second time execution
t2
t1
t1
t1
t2
t2
t1
t2
t2
t2
t1
t1
t1
t2
t2
t2
t1
t2
t1
t1
t2
t2
t1
t2
t1
t1
t1
t2
t1
t2
t2
t1
t2
t1
t2
t2
t1
t2
t1
t1
Tips and Tricks :
What are thread priorities? Is it a way that you can control scheduling?
Solution:Thread priorities might help you to influence the scheduler, but they still do not offer any
guarantee. Thread priorities are numerical values that tell the scheduler (if it cares) how important
a thread is to you. In general, the scheduler will kick a lower priority out of the running state if a
higher priority thread suddenly becomes runnable. Still, there is no guarantee. It is recommended
that you use priorities only if you want to influence performance, but never, ever rely on them for
program correctness.
Summary
‰  Once a thread is started, it will always enter the runnable state.
‰  The setPriority() method is use don Thread objects to give threads a priority of
between 1 (low) and 10 (high), although priorities are not guaranteed, and not all
JVMs recognize 10 distinct priority levels.
‰  If not explicitly set, a thread’s priority will have the same priority as the priority of the
thread that created it.
‰  The yield() method may cause a running thread to back out if there are runnable
threads of the same priority.
‰  The closest thing to a guarantee is that at any given time, when a thread is running it
will usually not have a lower priority than any thread in the runnable state. If a lowpriority thread is running when a high priority thread enters runnable, the JVM will
usually preempt the running low-priority thread and put the high-priority thread in.
Test Your Understanding
1.Which of the following are correct?
a)Threads are useful when mutuallyexclusive tasks are to be performed
b)Threads consume considerable amount of OS resources
c)Threads require synchronization when they access common resources
d)All the above
2.Which one of the following is not correct?
a)Every thread will go through the ‘waiting’ state during its lifetime
b)A thread will reach ‘dead’ state when the execution of its run() method is over
c)Every thread will start its life with the ‘new’ state
d)When the run() method of a thread is being executed, then it is said to be in
‘running’ state.
3.Name the different states in the life cycle of a thread.


37:Date and Properties classes

Learning Objectives
After completing this session, you will be able to:
‰  Identify java.util.Date and java.util.Properties classes
The Date Class
‰  Date class represents a precise momentin time, down to the millisecond.
‰  Dates are represented as a long type that counts the number of milliseconds since
midnight, January 1, 1970, Greenwich Mean Time.
The Date Class: Example
// Return the number of milliseconds in the Date
// as a long, using the getTime() method
Date d1 = new Date();
// timed code goes here
for (int i=0; i<1000000; i++) { int j = i;}
Date d2 = new Date();
long elapsed_time = d2.getTime() - d1.getTime();
System.out.println("That took " + elapsed_time
+ " milliseconds");
The Properties Class
‰  The Properties class represents a persistent set of properties.
‰  The properties can be saved to a stream or loaded from a stream:
‰  Typically a file
‰  Each key and its corresponding value in the property list is a string.
‰  A property list can contain another property list as its "defaults“. This second property
list is searched if the property key is not found in the original property list.
The Properties Class: Example
// set up new properties object
// from file "myProperties.txt"
FileInputStream propFile
= new FileInputStream("myProperties.txt");
Properties p
= new Properties(System.getProperties());
p.load(propFile);
// set the system properties
System.setProperties(p);
// display new properties
System.getProperties().list(System.out);
Try It Out
Problem Statement:
Write a program that illustrates the usage of java.util.Date class along with
java.util.GregorianCalendar and java.util.TimeZone classes in order to access date and time
information.
Code:
import java.util.*;
public class DateApp {
public static void main(String args[]) {
Date today = new Date();
GregorianCalendar cal = new GregorianCalendar();
cal.setTime(today);
System.out.println("Today: ");
displayDateInfo(cal);
cal.clear();
cal.set(2000, 0, 1);
System.out.println("\nNew Years Day 2000: ");
displayDateInfo(cal);
}
How It Works:
‰  The program creates a Date object and a GregorianCalendar object using the default
Date() and GregorianCalendar() constructors.
‰  The Date object is assigned to the today variable, and the GregorianCalendar object is
assigned to the cal variable.
‰  The cal variable is updated with the current date by invoking its setTime() method with
the Date object stored in today.
‰  The displayDateInfo() method is then invoked to display date and time information
about the cal variable.
‰  The clear() method of the Calendar class is invoked to reset the date of the
GregorianCalendar object stored in cal.
‰  The set() method is used to set its date to New Year's 2000. There are several
versions of the set() method, each of which takes a different set of parameters.
‰  The version used in DateApp takes the year, month, and date as parameters.
‰  Note that the month value ranges from zero to 12, where the year and date values
begin at one.
‰  The displayDateInfo() method is invoked again to display information about the new
calendar date.
‰  The displayDateInfo() method creates the days, months, and am_pm arrays to define
string values corresponding to the days of the week, months of the year, and a.m./p.m.
‰  It then prints a line corresponding to date and time values.
‰  These values are retrieved using the get() method of the Calendar class and the
Calendar constants corresponding to date and time values.
‰  The getTimeZone() method of Calendar is invoked to retrieve the local TimeZone
object.
‰  The getID() method of the TimeZone class is used to retrieve the local time zone ID
string.
Tips and Tricks:
Instead of using Date class, what is the alternate way to get the current time?
Solution:
‰  To get the current time use System.currentTimeMillis().
‰  However, the catch is that the time is provided in milliseconds.
‰  The value corresponds to the difference between the current time and midnight,
January 1, 1970 UTC.
‰  This method is useful for program timing studies.
Summary
‰  The classes you need to understand are java.util.Date, java.util.Calendar,
java.text.DateFormat, java.text.NumberFormat, and java.util.Locale.
‰  Most of the Date class’s methods have been deprecated.
‰  A Date is stored as a long, the number of milliseconds since January 1, 1970.
‰  Date objects are go-betweens the Calendar and Locale classes.
‰  The Calendar provides a powerful set ofmethods to manipulate dates, performing
tasks such as getting days of the week, or adding some number of months or years to
a date.
‰  The DateFormat.format() method is used to create Strings containing properly
formatted dates.
‰  The Locale class is used in conjunction with DateFormat and NumberFormat.
Test Your Understanding
1.Properties class is a subclass of the Hashtable class. Do you agree with this statement?
2.Which methods do you use to add and retrieve data in a Properties object?

36:Traversing Collections

Learning Objectives
After completing this session, you will be able to:
‰  Describe the two schemes ofTraversing Collections
‰  Define Iterator interface and Iterable Interface
‰  Apply Iterator
Two Schemes of Traversing Collections
The two schemes of traversing collections are:
‰  for-each:The for-each construct allows you to concisely traverse a collection or array
using a for loop
for (Object o: collection)
System.out.println(o);
‰  Iterator: An Iterator is an object that enablesyou to traverse through a collection and
to remove elements from the collection selectively, if desired.
Iterator Interface
public interface Iterator {
boolean hasNext();
Object next();
void remove(); //optional
}
‰  hasNext() method returns true if the iteration has more elements.
‰  next() method returns the next element in the iteration.
‰  remove() 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 Over for-each
‰  Iterator is used over for-each for removing 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.
static void filter(Collection<?> c) {
for (Iterator<?> it = c.iterator(); it.hasNext(); )
if (!cond(it.next()))
it.remove();
}
‰  Iterating over multiple collections in parallel
The Iterable Interface
‰  Iterable is a generic interface that was added by Java 2, v5.0.
‰  The Iterable interface must be implemented byany class whose objects will be applied
by the for-each version of the for loop.
‰  In other words, a class must implement Iterable whenever an object needs to be used
within a for-each style for loop in that class.
‰  Iterable has the following declaration:
interface Iterable<T>
‰  It defines one method, iterator() , as shown here:
Iterator<T> iterator()
‰  It returns an iterator to the set of elements contained in the invoking object.
‰  Although the for-each form of the for loop was designed with arrays and collections in
mind, it can be used to cycle through the contents of any object that implements the
Iterable interface.
‰  This enables you to create classes whose objects can be applied with the for-each
form of the for loop.
‰  This is a powerful feature that substantially increases the types of programming
situations to which the for can be applied.
Try It Out
Problem Statement:
Write a program that illustrates the usage of List and an Iterator.
Code:
import java.util.*;
class Dog {
public String name;
Dog(String n) {
name = n;
}
}
class IteratorTest {
public static void main(String[] args) {
List<Dog> d = new ArrayList<Dog>();
Dog dog = new Dog("aiko");
d.add(dog);
d.add(new Dog("clover"));
d.add(new Dog("magnolia"));
Iterator<Dog> itr = d.iterator(); // make an iterator
while (itr.hasNext()) {
Dog d2 = itr.next(); // cast not required
System.out.println(d2.name);
}
How It Works:
‰  When you run IteratorTest, it displays the following results:
aiko
clover
magnolia
size 3
get1 clover
aiko 0
oa aiko
oa clover
‰  Firstly, you have used generics syntax to create the Iterator (an Iterator of type Dog).
‰  Because of this, when you have used the next() method, you did not have to cast the
object returned by next() to a Dog.
‰  You could have declared the Iterator like this (on using JDK1.4 or lesser version):
Iterator itr = d.iterator; // make an Iterator
‰  But then you would have had to cast the following returned value:
Dog d2 = (Dog)itr.next();
‰  The rest of the code demonstrates using the size() , get() , indexOf() , and toArray()
methods.
‰  Note:Invoking hasNext() does not move the iterator to the next element of the
collection.
Tips and Tricks:
Explain briefly about the ConcurrentModificationException related to Iterators.
Solution:
‰  ConcurrentModificationException exception (extends RuntimeException) may be
thrown by methods that have detected concurrent modification of a backing object
when such modification is not permissible.
‰  For example, it is not permissible for one thread to modify a Collection while another
thread is iterating over it. In general, the results are undefined under these
circumstances. Some Iterator implementations (including those of all the collection
implementations provided by the JDK) may choose to throw this exception if this
behavior is detected. Iterators that do this are known as fail-fast iterators, as they fail
quickly and cleanly, rather that risking arbitrary behavior that is not deterministic at an
undetermined time in the future.
Summary
‰  Iterable is a generic interface that was added by Java 2, v5.0.
‰  Iterable contains only one method as shown below:
Iterator<T> iterator()
‰  The earlier method returns an Iterator to the elements contained in the invoking object.
‰  Because the iterator() method of Iterable returns an Iterator, often a class that
implements Iterable will also implement Iterator.
‰  Iterator is a generic class in Java 2, v5.0, when the entire Collections Framework was
retrofitted for generics.
‰  Earlier versions of Iterator were not generic.

35: Set List Map Queue

Learning Objectives
After completing this session, you will be able to:
‰  Set Interface and Implementations
‰  List Interface and Implementations
‰  Map Interface and Implementations
‰  Queue Interface and Implementations
‰  Define Abstract Classes
‰  Explain Routine Data Manipulation
‰  Describe Searching
‰  Define Composition
“Set” Interface
The Set interface is a collection that cannot contain duplicate elements.
The Set interface models the mathematical set abstraction and is used to represent sets:
‰  Cards comprising a poker hand
‰  Courses making up the schedule of a student
‰  The processes running on a machine
The Set interface contains only methods inherited from Collection and adds the restriction to
prohibit the duplicate 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();
// 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);
}
“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 meaningfullyeven if their implementation types differ. Two
Set instances are equal if theycontain the same elements.
“SortedSet” Interface
Sorted Set interface is 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.
Implementations of “Set” Interface
The implementations of Set interface are:
‰  HashSet
‰  TreeSet
‰  LinkedHashSet
HashSet
‰  HashSet is much faster than TreeSet (constant-time versus log-time for most
operations) but offers no ordering guarantees.
‰  HashSet is the mostly commonly used implementation.
Caveats of Using HashSet
Iteration is linear in the sum of the number of entries and the number of buckets (the capacity):
‰  Choosing an initial capacity that is too high, can waste both space and time
‰  Choosing an initial capacity that is too low,wastes time by copying the data structure
each time it is forced to increase its capacity
Example: Set Interface and 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);
}
}
public class SetExample {
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);
}
}
For example, the numbers 1, 2, 3, and 4 can be added in the following ways:
‰  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
‰  The TreeSet is one of two sorted collections (the other being TreeMap).
‰  No duplicates, iterates in sorted order.
‰  It generally guarantees that the elements will be in ascending order, according to
natural order.
Example: Set Interface and TreeSet
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);
}
Result: Members from TreeSet = [four, one, three, two]
LinkedHashSet
‰  LinkedHashSet is 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.
‰  It spares its clients from the unspecified, generally chaotic ordering provided by
HashSet without incurring the increased cost associated with TreeSet.
Example: Set Interface and LinkedHashSet
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);
}
Result: Members from LinkedHashSet = [2, 1, 3]
“List” Interface
‰  List interface is an ordered collection (sometimes called a sequence).
‰  Lists can contain duplicate elements.
‰  The user of a List interface generally has precise control over where in the each list
element is inserted and can access elements by their integer index (position).
Additional Operations Supported by “List” Interface over “Collection”
The additional operations supported by List interface over Collection interface are:
‰  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 sequential nature of the
list.
‰  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
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);
}
Implementations of “List” Interface
The implementations of List interface are:
‰  ArrayList:
oOffers constant-time positional access
oGives you fast iteration and fast random access
oIt is an ordered collection (by index), but not sorted
oMost commonly used implementation
‰  LinkedList:You use it frequently to add elements to the beginning of the List or
iterate over the List to delete elements from its interior
“Map” Interface
‰  Map interface handles key or value pairs.
‰  A Map interface cannot contain duplicate keys. Each key can map to at most one
value.
“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();
// Bulk operations
void putAll(Map<? extends K, ? extends V> m);
void clear();
// Collection Views
public Set<K> keySet();
public Collection<V> values();
public Set<Map.Entry<K,V>> entrySet();
// Interface for entrySet elements
public interface Entry {
K getKey();
V getValue();
V setValue(V value);
}
“SortedMap” Interface
‰  A Map interface that maintains its mappings in ascending key order is called the
SortedMap interface. This is the Map analog of SortedSet.
‰  Sorted maps are used for naturally ordered collections of key or value pairs, such as
dictionaries and telephone directories.
Implementations of “Map” Interface
The implementations of the Map interface are:
‰  HashMap:You use this if you want maximum speed and do not want to care about
iteration order. Most commonly used implementation.
‰  TreeMap:You use this when you need SortedMap operations or key-ordered
Collection-view iteration.
‰  LinkedHashMap:Although it will be somewhat slower than HashMap for adding and
removing elements, you can expect faster iteration with a LinkedHashMap.
“Queue” Interface
‰  Queue interface is a collection used to hold multiple elements prior to processing.
‰  Besides basic Collection operations, a Queue interface provides additional insertion,
extraction, and inspection operations.
‰  Typically, but do not necessarily, Queue interface order elements in a FIFO (First-In,
First-Out) manner.
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 natural ordering of the elements or the ordering imposed by an
explicit Comparator.
Implementations of Queue Interface
Concurrent Queue implementations:The java.util.concurrent package contains a set of
synchronized Queue interfaces and classes. BlockingQueue extends Queue with operations that
wait for the queue to become nonempty when retrieving an element and for space to become
available in the queue when storing an element. This interface is implemented by the following
classes:
‰  LinkedBlockingQueue:An optionally bounded FIFO blocking queue backed by
linked nodes
‰  ArrayBlockingQueue:A bounded FIFO blocking queue backed by an array
‰  PriorityBlockingQueue:An unbounded blocking priority queue backed by a heap
‰  DelayQueue:A time-based scheduling queue backed by a heap
‰  SynchronousQueue:A simple rendezvous mechanism that uses the BlockingQueue
interface
Abstract Classes
Abstract classes include the following abstract implementations:
‰  AbstractCollection
‰  AbstractSet
‰  AbstractList
‰  AbstractSequentialList
‰  AbstractMap
Routine Data Manipulation
The Collections class provides five algorithms for doing routine data manipulation on List objects:
‰  reverse reverses the order of the elements in a List
‰  fill overwrites every element in a List with the specified value and this operation is useful for reinitializing a List
‰  copy takes two arguments, namely 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, then the remaining elements
in the destination List are unaffected.
‰  swap swaps the elements at the specified positions in a List.
‰  addAll adds all the specified elements to a Collection. The elements to be added may
be specified individually or as an array.
Searching
The Collections class has binarySearch() method for searching a specified element in a sorted List
// 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);
Composition
‰  Collections.frequency(l) counts the number of times the specified element occurs in
the specified collection.
‰  Collections.disjoint(l1, l2) determines whether two Collections are disjoint that is,
whether they contain no elements in common. The Collections class has
binarySearch() method for searching a specified element in a sorted List.
Try It Out
Problem Statement:
Write a program that illustrates the usage of Set interface and its implementation class namely
HashSet.
Code:
import java.util.*;
public class SetApp {
public static void main(String args[]) {
HashSet set = new HashSet();
set.add("This");
set.add("is");
set.add("is");
set.add("a");
set.add("a");
set.add(null);
set.add("test");
displaySet(set);
}
// continued …
Refer File Name: SetApp.javato obtain soft copy of the program code
How It Works:
‰  SetApp begins by creating a HashSet object and assigning it to the set variable. It then
adds the same elements to the set as ListApp did to its list.
‰  Note that because sets are not ordered, there are no addFirst() and addLast()
methods.
‰  The displaySet() method is invoked to display the set.
‰  When you run SetApp, it displays the following results:
The size of the set is: 5
This
is
a
null
test
‰  Note that the set does not allow duplicate elements, but allows the null value as an
element.
‰  The displaySet() method uses the size() method to determine the number of elements
in the set.
‰  It uses the iterator() method to create an Iterator object.
‰  The Iterator object is used to step through and display the elements of the set.
Tips and Tricks:
Provide the implementing classes in the collection interfaces for the data structures namely
HashTable, ResizableArray, BalancedTree, and LinkedList.
Solution:
Note:Some of the operations in the collection interfaces are optional, meaning that the
implementing class may choose not to provide a proper implementation of such an operation. In
such a case, an UnsupportedOperationException isthrown when that operation is invoked.

34:Collections and Util package

Learning Objectives
After completing this session, you will be able to describe the following:
‰  Define collections
‰  Describe the importance of collections
‰  Identify Core Collection Interfaces
‰  List the implementations
Collection
‰  A “collection” object 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.
Typically, they represent data items that forma natural group, such as a poker hand (a
collection of cards), a mail folder (a collection of letters), or a telephone directory (a
mapping of names to phone numbers).
Collection Framework
A collections framework is a unified architecturefor representing and manipulating collections.
All collections frameworks contain the following:
‰  Interfaces
‰  Implementations
‰  Algorithms
Benefits of Collection Framework
The benefits of collection framework are:
‰  Reduces programming effort
‰  Increases program speed and quality
‰  Allows interoperability among unrelated APIs: 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: New data structuresthat conform to the standard collection
interfaces are by nature reusable
Collection Interfaces
‰  Collection interfaces are abstract data types that represent collections. Collection
interfaces are in the form of Java interfaces.
‰  Interfaces allow collections to be manipulated independently of the implementation
details of their representation, which is called the polymorphic behavior.
‰  In Java programming language (and other object-oriented languages), interfaces
generally form a hierarchy. You chooseone that meets your need as a type.
Implementations
‰  Implementations are the data objects used to store collections, which implement the
interfaces.
‰  Each of the implementations for general purpose (you will see in the following slide)
provide all optional operations contained in its interface.
‰  Java Collections Framework also provides several implementations for special
purpose situations that require nonstandard performance, usage restrictions, or other
unusual behavior.
Types of Implementations
The types of implementations are:
‰  General-purpose implementations
‰  Special-purpose implementations
‰  Concurrent implementations
‰  Wrapper implementations
‰  Convenience implementations
‰  Abstract implementations
General Purpose Implementations












Algorithms
‰  These are the methods that perform useful computations, such as searching and
sorting, on objects, which implement collection interfaces.
‰  The algorithms are said to be polymorphic that is, the same method can be used on
many different implementations of the appropriate collection interface. In essence,
algorithms are reusable functionality.
Core Collection Interfaces Hierarchy
The hierarchy of Core Collection Interfaces are shown in the following figure:















Core Collection Interfaces
‰  Core Collection Interfaces are the foundation of the Java Collections Framework.
‰  Core Collection Interfaces form an inheritance hierarchy among themselves.
‰  You can create a new collection interface from them (highly likely you do not have to).
“Collection” Interface
‰  Collection interface is the rootof the collection hierarchy.
‰  Collection interface is the least common denominator that all collections implement.
Every collection object is a type of Collection interface.
‰  Collection interface is used to pass collection objects around and to manipulate them
when maximum generality is desired. Apply Collection interface as a type.
‰  JDK (Java Development Kit) does not provide any direct implementations of this
interface but provides implementations of more specific sub interfaces, such as Set
and List.
“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();
// 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);
}
Example: Usage “Collection” Interface as a Type
// Create a ArrayList collection object instance and assign it
// to Collection type.
Collection c1 = new ArrayList();
// Use methods of Collection interface.
//
// Polymorphic behavior is expected. For example,
// the add() implementation of ArrayList class will be
// invoked. For example, depending on the implementation,
// duplication is allowed or not allowed.
boolean b1 = c1.isEmpty();
boolean b2 = c1.add(new Integer(1))
add() and remove() Methods of Collection Interface
‰  The add() method is defined generally enough so that it makes sense for collections,
which allow duplicates as well as those that do not.
‰  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. add()
method of Set interface follows “no duplicate” rule.
Bulk Operations
The various bulk operations are:
‰  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. It retains only those elements in the target
Collection that are also contained in the specified Collection.
‰  clear() removes all elements from the Collection.
Example: removeAll()
‰  removeAll() removes all instances of a specified element, e, from a Collection, c:
c.removeAll(Collections.singleton(e));
‰  removeAll() removes all of the null elements from a Collection:
c.removeAll(Collections.singleton(null));
‰  Collections.singleton() , which is a static factory method returns an immutable Set
containing only the specified element.
Array Operations
‰  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.
Example: Array Operations
The simple form with no arguments creates a new array of Object.
Object[] a = c.toArray();
Suppose c is known to contain only strings. The following snippet dumps the contents of c into a
newly allocated array of String whose length is identical to the number of elements in c.
String[] a = c.toArray();
Try It Out
Problem Statement:
Write a program that illustrates the usage of ArrayList class, which is implemented from the List
interface.
Code:
import java.util.*;
public class TestArrayList {
public static void main(String[] args) {
List<String> test = new ArrayList<String>();
String str = "hi";
test.add("string");
test.add(str);
test.add(str + str);
System.out.println(test.size());
System.out.println(test.contains(42));
System.out.println(test.contains("hihi"));
test.remove("hi");
System.out.println(test.size());
}
}


Tips and Tricks:
List out key points on String Buffers.
Solution:
‰  String Buffers are mutable strings.
‰  StringBuffer is a final class.
‰  They can be created empty, from a string orwith a capacity. An empty StringBuffer is
created with 16-character capacity. A StringBuffer created from a String has the
capacity of the length of String + 16. StringBuffer created with the specified capacity
has the exact capacity specified. As they can grow dynamically in size without bounds,
capacity does not have much effect.
‰  append, insert, setCharAt, and reverse are used to manipulate the string buffer.
‰  setLength changes the length. If the current content is larger than specified length,
then it is truncated. If it is smaller than the specified length, then nulls are padded. This
method does not affect the capacity.
‰  equals on StringBuffer does a shallow comparison (same like ==) and will return true
only if the objects are same. Do not use it to test content equality.
‰  trim is not a StringBuffer method.
‰  There is no relationship between String and StringBuffer. Both extend Object class.
‰  String context means, ‘+’ operator appearing with one String operand. String
concatenation cannot be applied to StringBuffer.
‰  A new StringBuffer is created.
‰  All operands are appended by calling toString method, if needed.
‰  Finally a string is returned by calling toString on the StringBuffer.

Summary
‰  Common collection activities include adding objects, removing objects, verifying object
inclusion, retrieving objects, and iterating.
‰  Three meanings for “collection”:
oCollection: Represents the data structure in which objects are stored
oCollection: java.utilinterface from which Set and List extend
oCollections: A class that holds static collection utility methods
‰  Four basic sub-flavors of collections: Sorted, Unsorted, Ordered, Unordered
oOrdered: Iterating through a collection in a specific, non-random order.
oSorted: Iterating through a collection in a sorted order.
‰  Sorting can be alphabetic, numeric, or programmer-defined.
Test Your Understanding
1.State true or false for the following:
a)The Collection interface helps you to workwith collection of objects. This interface
is at the top of the collections hierarchy.The collections framework is built on this
interface.
b)Certain static methods, which operate on collections, are defined in the
Collections class. Such methods are known as algorithms.



33:StringBuffer and StringBuilder

Learning Objectives
After completing this session, you will be able to:
‰  Define StringBuffer and StringBuilder
The StringBuffer Class
Problem with String objects: Once created, can no longer be modified (It is a final class)
A StringBuffer object:
‰  Similar to a String object
‰  But, mutable or can be modified:
‰  Unlike String in this aspect
‰  Length and content may get changed through some method calls
The StringBuffer Class: Methods
The StringBuffer Class: Example
1 class StringBufferDemo {
2 public static void main(String args[]) {
3 StringBuffer sb = new StringBuffer("Jonathan");
4 System.out.println("sb = " + sb);
5 /* initial capacity is 16 */
6 System.out.println("capacity of sb: "+sb.capacity());
7 System.out.println("append \'O\' to sb: " +
8 sb.append('O'));
9 System.out.println("sb = " + sb);
10 System.out.println("3rd character of sb: " +
11 sb.charAt(2));
12
13 char charArr[] = "Hi XX".toCharArray();
14 /* Need to add 1 to the endSrc index of getChars */
15 sb.getChars(0, 2, charArr, 3);
16 System.out.print("getChars method: ");
17 System.out.println(charArr);
18 System.out.println("Insert \'jo\' at the 3rd cell: "
19 + sb.insert(2, "jo"));
20 System.out.println("Delete \'jo\' at the 3rd cell: "
21 + sb.delete(2,4));
22 System.out.println("length of sb: " + sb.length());
23
24 System.out.println("replace: " +
25 sb.replace(3, 9, " Ong"));
26 /* Need to add 1 to the endIndex parameter of
27 substring*/
28 System.out.println("substring (1st two characters): "
29 + sb.substring(0, 3));
30 System.out.println("implicit toString(): " + sb);
31 }
32 }
The java.lang.StringBuilder Class
‰  J2SE5.0 added the StringBuilder class, which is a drop-in replacement for StringBuffer
in cases where thread safety is not an issue.
‰  Because StringBuilder is not synchronized,it offers faster performance than
StringBuffer.
‰  In general, you should apply StringBuilder in preference over StringBuffer. In fact, the
J2SE 5.0 javac compiler normally uses StringBuilder instead of StringBuffer whenever
you perform string concatenation as in System.out.println("The result is " + result);
‰  All the methods available on StringBuffer are also available on StringBuilder, so it
really is a drop-in replacement.
‰  StringBuilder is identical to the well-known StringBuffer class of Java except for one
important difference it is not synchronized, which means it is not thread-safe.
‰  The advantage of using StrignBuilder is faster performance.
‰  However, in cases in which you are applying multithreading, you must apply
StringBuffer rather than StringBuilder.
‰  The String class defines a new constructor that enables you to construct a String from
a StringBuilder as shown in the following code:
String(StringBuilder strBuildObj)
Try It Out
Problem Statement:
Write a program that illustrates the manipulation of the StringBuffer objects using the append() ,
insert() , and setCharAt() methods.
Code:
public class StringBufferApp {
public static void main(String args[]) {
StringBuffer sb = new StringBuffer(" is ");
sb.append("Hot");
sb.append('!');
sb.insert(0, "Java");
sb.append('\n');
sb.append("This is ");
sb.append(true);
sb.setCharAt(21, 'T');
sb.append('\n');
sb.append("Java is #");
sb.append(1);
String s = sb.toString();
System.out.println(s);
}
}
Refer File Name: StringBufferApp.javato obtain soft copy of the program code
How It Works:
‰  The program creates a StringBuffer object using the string " is ". It appends the string
"Hot" using the append() method and the character '!' using an overloaded version of
the same method.
‰  The insert() method is used to insert the string "Java" at the beginning of the string
buffer.
‰  Three append methods are used respectively to tack on the following:
oA new line character (\n), the string "This is ", and the boolean value true.
‰  The append() method is overloaded to support the appending of the primitive data
types as well as arbitrary Java objects.
‰  The setCharAt() method is used to replace the letter 't' at index 21 with the letter 'T‘ .
The charAt() and setCharAt() methods allow StringBuffer objects to be treated as
arrays of characters.
‰  Finally, another newline character is appended tosb, followed by the string "Java is #"
and the int value 1.
‰  The StringBuffer object is then converted toa string and displayed to the console
window.
‰  The output of the program is as follows:
Java is Hot!
This is True
Java is #1
Tips and Tricks:
List out key points on String Buffers.
Solution:
‰  String Buffers are mutable strings.
‰  StringBuffer is a final class.
‰  They can be created empty, from a string orwith a capacity. An empty StringBuffer is
created with 16-character capacity. A StringBuffer created from a String has the
capacity of the length of String + 16. StringBuffer created with the specified capacity
has the exact capacity specified. As they can grow dynamically in size without bounds,
capacity does not have much effect.
‰  append, insert, setCharAt, and reverse are used to manipulate the string buffer.
‰  setLength changes the length. If the current content is larger than specified length,
then it is truncated. If it is smaller than the specified length, then nulls are padded. This
method does not affect the capacity.
‰  equals on StringBuffer does a shallow comparison (same like ==) and will return true
only if the objects are same. Do not use it to test content equality.
‰  trim is not a StringBuffer method.
‰  There is no relationship between String and StringBuffer. Both extend Object class.
‰  String context means, ‘+’ operator appearing with one String operand. String
concatenation cannot be applied to StringBuffer.
‰  A new StringBuffer is created.
‰  All operands are appended by calling toString method, if needed.
‰  Finally a string is returned by calling toString on the StringBuffer.
Summary
‰  The StringBuffer’s API is the same as the new StringBuilder’s API, except that
StringBuilder’s methods are not synchronized for thread safety.
‰  StringBuilder methods should run faster than StringBuffer methods.
‰  All of the following apply to both StringBuffer and StringBuilder:
‰  They are mutable – they can change without creating a new object.
‰  StringBuffer methods act on the invoking object, and objects can change without an
explicit assignment in the statement.
‰  StringBuffer equals() is not overridden; it doesn’t compare values.
‰  StringBuffer methods to remember: append(), delete(), insert(), reverse(), and
toString().

32:equals() method and hashCode() method

Learning Objectives
After completing this session, you will be able to:
‰  Identify equals() method and hashCode() method
Java Object Law for equals() and hashCode() Methods
The Java API docs for the class Object state the following rules that a Java programmer must
adhere:
‰  If two objects are equal, then theymust have matching hashcodes.
‰  If two objects are equal, then calling equals() on the other object must return true. In
other words, if (a.equals(b)), then (b.equals(a)) .
‰  Java Object Law for equals() and hashCode() Methods (Contd.)
‰  If two objects have the same hashcode value, then they are not required to be equal.
But if they are equal, they must have the same hashcode value. So, if you override
equals() , you must override hashCode() .
‰  The default behavior of hashCode() is to generate a unique integer for each object on
the heap. So if you do not override hashCode() in a class, then no two objects of that
type can ever be considered equal.
‰  The default behavior of equals() is to do a == comparison. In other words, the default
behavior of equals() is to test whether the two references refer to a single object on
the heap. So if you do not override equals() in a class, then no two objects can ever be
considered equal because references to two different objects will always contain a
different bit pattern.
‰  a.equals(b) must also mean thata.hashCode() == b.hashCode().
‰  But, a.hashCode() == b.hashCode() does not have to mean a.equals(b).
Try It Out
Problem Statement:
Write a program that illustrates the usage of equals() and hashCode() methods.
Code:
class HashHash {
public int x;
public HashHash(int xVal) {
x = xVal;
}
public boolean equals(Object obj) {
HashHash h = (HashHash) obj;
if (h.x == this.x) {
return true;
} else {
return false;
}
}
public int hashCode() {
return (x * 17);
}
// continued …
Refer File Name: HashHash.javato obtain soft copy of the program code
How It Works:
‰  This program has overridden both the equals() and hashCode() methods.
‰  Notice that in order for an object to be located, the search object and the object in the
collection must have both identical hashcodevalues and return true for the equals()
method.
‰  So there is just no way out of overridingboth methods to be absolutely certain that
your objects can be applied in Collections that implement hashing.
Tips and Tricks:
How come hashcodes can be the same even if objects are not equal?
Solution:
‰  HashSets use hashcodes to store the elements in a way that makes it much faster to
access. If you try to find an object in an ArrayList by giving the ArrayList a copy of the
object (as opposed to an index value), then the ArrayList has to start searching from
the beginning, looking at each element in the list to see if it matches. But a HashSet
can find an object more quickly, because it uses the hashcode as a kind of label on
the “bucket” where it stored the element.
‰  Hashcodes can be the same without necessarily guaranteeing that the objects are
equal, because the “hashing algorithm” applied in the hashCode() method might
happen to return the same value for multiple Objects. This means that multiple objects
would all land in the same bucket in the HashSet.
‰  Hashcode values are sometimes used to narrow down the search, but to find the one
exact match, the HashSet still has to take all the objects in that one bucket (the bucket
for all objects with the same hashcode) and then call equals() on them to see if the
object it is looking for is in that bucket.
Summary
‰  equals(), hashCode(), and toString() are public.
‰  When overridding equals(), use the instanceof operator to be sure you are evaluating
an appropriate class.
‰  Highlights of the equals() contract:
oReflexive: x.equals(x) is true.
oSymmetric: if x.equals(y) is true, then y.equals(x) must be true.
oTransitive: if x.equals(y) is true, and y.equals(z) is true, then z.equals(x) is true.
oConsistent: Multiple calls to x.equals(y) will return the same result.
oNull: If x.equals(y) is true, then x.hashCode() == y.hashCode() is true.
oIf you override equals(),override hashCode().
‰  Highlights of the hashCode() contract:
oConsistent: multiple calls to x.hashCode() return the same integer.
oIf x.equals(y) is true, x.hashCode() == y.hashCode() is true.
oIf x.equals(y) is false, then x.hashcode() == y.hashCode() can be either true or
false, but false will tend to create better efficiency.
otransient variables are not appropriate for equals() and hashCode().
Test Your Understanding
1.State true or false for the following:
a)If two objects are equal, then they must have matching hashcodes.
b)a.equals(b) must also mean that a.hashCode() == b.hashCode()
c)a.hashCode() == b.hashCode() must also mean that a.equals(b)