Core Java: Collections Java 1.5 Features Exceptions and Error Handling
Core Java: Collections Java 1.5 Features Exceptions and Error Handling
Core Java: Collections Java 1.5 Features Exceptions and Error Handling
Collections
Java 1.5 features
Exceptions and Error handling
Collections
Collection
Interface
Class
Set List Queue
Interface
Implementation
Inheritance
HashSet ArrayList Vector
SortedSet
LinkedList
Stack
TreeSet
Map
HashMap TreeMap
// 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);
}
import java.util.*;
public class SetInterfaceEx{
public static void main(String[] args) {
int a[] = {5,2,9,4,1};
Set <Integer> hs = new HashSet<Integer>();
for(int i=0;i<a.length;i++) hs.add(new Integer(a[i]));
System.out.println(hs.size() + " The HashSet is " + hs);
Set <Integer> lhs = new LinkedHashSet<Integer>();
for(int i=0;i<a.length;i++) lhs.add(new Integer(a[i]));
System.out.println(hs.size() + " The LinkedHashSet is " + lhs);
Set <Integer> ts = new TreeSet<Integer>();
for(int i=0;i<a.length;i++) ts.add(new Integer(a[i]));
System.out.println(hs.size() + " The TreeSet is " + ts);
}
}
HashSet is a good choice for representing sets if you don't care about
element ordering. But if ordering is important, then LinkedHashSet or
TreeSet are better choices. However, LinkedHashSet or TreeSet come with
an additional speed and space cost.
Iteration over a LinkedHashSet is generally faster than iteration over a
HashSet.
Tree-based data structures get slower as the number of elements get larger
HashSet and LinkedHashSet do not represent their elements in sorted order
Because TreeSet keeps its elements sorted, it can offer other features such
as the first and last methods,i.e the lowest and highest elements in a set,
respectively.
If there are more elements, nextElement() will return the next element as an
Object.
If there are no more elements when nextElement() is called, the runtime
NoSuchElementException will be thrown.
import java.util.Enumeration;
import java.util.Vector;
public class MainClass {
public static void main(String args[]) throws
Exception {
Vector v = new Vector();
v.add("a");
v.add("b");
v.add("c");
Enumeration e = v.elements();
while (e.hasMoreElements()) {
Object o = e.nextElement();
System.out.println(o);
}
}
}
21 Core Java | Muralidhar V
Iterator interface
import java.util.ArrayList;
import java.util.Collection;
import java.util.Iterator;
Using HashSet
Set hashSet = new HashSet();
hashSet.add(“Yellow”);
hashSet.add(“White ”);
hashSet.add(“Green”);
hashSet.add(“Orange”);
System.out.println(“An unsorted set of strings”);
System.out.println(hashSet + “\n”);
Output: An unsorted set of strings
[Orange, Green, White, Yellow]
Using TreeSet
Set treeSet = new TreeSet(hashSet);
System.out.println(“Sorted set of strings”);
System.out.println(treeSet + “\n”);
Output: A sorted set of strings
List
The Vector class implements a
growable array of objects.
Vector Like an array, it contains
+addElement(element: Object) : void components that can be accessed
+capacity() : void using an integer index.
+copyInto(anArray: Object[]) : void
+elementAt(index: int) : Object
+elements() : Enumeration
However, the size of a Vector can
+ensureCapacity() : void grow or shrink as needed to
+firstElement() : int
+insertElementAt(index: int) : void accommodate adding and removing
+lastElement() : Object items after the Vector has been
+removeAllElements() : void
+removeElement(element: Object) : void created.
+removeElementAt(index: int) : void
+setElementAt(element: Object, index: int) : void
+setSize(newSize: int) : void
+trimToSize() : void
+empty() : boolean
+peek() : Object
+pop() : Object
+push(element: Object) : void
+search(element: Object) : int
This example presents two programs to rewrite Example 5.2, using a vector
and a stack instead of an array, respectively.
The program reads student scores from the keyboard, stores the scores in the
vector, finds the best scores, and then assigns grades for all the students.
A negative score signals the end of the input.
A Map is a storage that maps keys to values. There cannot be duplicate keys
in a Map and each key maps to at most one value.
The Map interface is not an extension of Collection interface. Instead the
interface starts of it’s own interface hierarchy.
for maintaining key-value associations. The interface describes a mapping
from keys to values, without duplicate keys, by definition.
The Map interface maps keys to the elements. The keys are like indexes. In
List, the indexes are integer. In Map, the keys can be any objects.
void clear()
– Removes all mappings from this map (optional operation).
boolean containsKey(Object key)
– Returns true if this map contains a mapping for the specified key.
boolean containsValue(Object value)
– Returns true if this map maps one or more keys to the specified value.
Set<Map.Entry<K,V>> entrySet()
– Returns a set view of the mappings contained in this map.
boolean equals(Object o)
– Compares the specified object with this map for equality.
V get(Object key)
–
Returns the value to which this map maps the specified key.
int hashCode()
– Returns the hash code value for this map.
boolean isEmpty()
– Returns true if this map contains no key-value mappings.
Set<K> keySet()
– Returns a set view of the keys contained in this map.
V put(K key, V value)
–
Associates the specified value with the specified key in this map (optional
operation).
void putAll(Map<? extends K,? extends V> t)
– Copies all of the mappings from the specified map to this map (optional operation).
V remove(Object key)
– Removes the mapping for this key from this map if it is present (optional operation).
int size()
– Returns the number of key-value mappings in this map.
Collection<V> values()
– Returns a collection view of the values contained in this map.
The HashMap and TreeMap classes are two concrete implementations of the
Map interface. Both will require key &value. Keys must be unique.
The HashMap class is efficient for locating a value, inserting a mapping, and
deleting a mapping.
The TreeMap class, implementing SortedMap, is efficient for traversing the
keys in a sorted order.
HashMap allows null as both keys and values
TreeMap is slower than HashMap
TreeMap allows us to specify an optional Comparator object during its
creation. This comparator decides the order by which the keys need to be
sorted.
Overloaded fill method for char, byte, short, int, long, float, double,
and Object.
Overloaded sort method for char, short, int, long, float, double, and
Object.
This example demonstrates using the methods in the Arrays class. The
example creates an array of int values, fills part of the array with 50, sorts it,
searches for an element, and compares the array with another array.
(See the Companion site)
TestArrays
41 Core Java | Muralidhar V
Ordering the objects
Comparable interface and Comparator Interface
import java.util.*;
public class StudentComparator
implements Comparator<Student> {
public int compare(Student s1, Student s2) {...}
public boolean equals(Object o1) {...}
}
Note: When we are using this Comparator, we don’t need the compareTo
method in the Student class
Because of generics, our compare method can take Student arguments
instead of just Object arguments
We have
Comparator<Student> comp = new StudentComparator();
TreeSet<Student> set = new TreeSet<Student>(comp);
Comparator<Student> myStudentNameComparator =
new MyStudentNameComparator();
TreeSet studentsByName =
new TreeSet(myStudentNameComparator);
studentsByName.addAll(studentsByScore);
Generic classes
New approach to loops – for / in statements
Static imports
Arrays, string builder, queues and overriding return type
Annotation
Output formatting – format() and printf()
Autoboxing of primitive types
Enumerated types
Variable length of arguments
Similar in usage to C++ templates, but do NOT generate code for each
implementation
Ensure stored/retrieved type of objects
Check done at compile-time – avoid nasty casting surprises during runtime
Generics are removed from compiled classes – backward compatilibity, no
additional code
Can be used in legacy code to check for place where incorrect type is inserted
Access to “template” class methods without casting
Example:
– Iterator iter = integerStack.iterator();
while (iter.hasNext()) {
System.out.println(iter.next());
}
Instead of
void cancelAll(Collection c) {
for (Iterator i = c.iterator(); i.hasNext(); ) {
TimerTask tt = (TimerTask) i.next();
tt.cancel();
}
}
You will be able to use:
void cancelAll(Collection<TimerTask> c) {
for (TimerTask task : c)
task.cancel();
}
What does the JDK 1.5 compiler handle automatically for us?
Not everyone likes this syntax! How else could it have been done?
void cancelAll(Collection<TimerTask> c) {
foreach TimerTask task of c) //C# notation
task.cancel();
}
65 Core Java | Muralidhar V
Static import
Enables one to refer to static constants from a class without needing to inherit
from it.
If only used occasionally this technique is not very useful, but in complex
cases this technique help simplify coding.
double x, y;
x = ceil(y); // can use method name directly
hashCode
– Returns a hash code based on the contents of the specified array.
– For any two arrays a and b such that Arrays.equals(a, b) is it also the case that
Arrays.hashCode(a) == Arrays.hashCode(b)
deepEquals
– Returns true if the two specified arrays are deeply equal to one another.
toString
– Returns a string representation of the contents of the specified array. String
representation is a list of the array’s elements, enclosed in square brackets (“[]”).
Adjacent elements separated by “, “
Extends Collection
Designed for holding elements prior to processing.
Typically ordered in a FIFO manner.
Main Methods
– remove() and pull()
Both return the head of the queue.
When empty, the remove() method throws an exception while poll() returns null.
Allows the user to have a method in inherited class with same signature as in
parent’s class but differing only in return types.
Makes programs more readable and solves casting problem
class Shape
{
public Shape transform(int x, int y)
}
Example
/* @author Jack */
public final class AnnotationsTest {
@Overrides
public String toString(int i) { return “ x “ };
}
In addition, some Java classes like Date and BigInteger also have formatting
rules. See the java.util.Formatter class for more information.
Before
ArrayList<Integer> list = new ArrayList<Integer>();
list.add(0, new Integer(42));
int total = (list.get(0)).intValue();
5.0 version:
ArrayList<Integer> list = new ArrayList<Integer>();
list.add(0, 42);
int total = list.get(0);
myMethod(“a”);
myMethod(“a”, “b”, “c”, “d”, “e”);
myMethod();
Provides basic input functionality for reading data from system console or any
data stream
Following example reads a String from standard input and expects a following
int value:
Scanner s=Scanner.create(System.in);
String param= s.next();
int value=s.nextInt();
s.close();
– Scanner methods next and nextInt block if no data is available
– Supports regular expression based search
To process more complex input, pattern matching algorithms are available
from class java.util.Formatter
Threading
– There are many new features for controlling synchronization and threading which
increase performance and prevent that you have to write synchronization
primitives yourself.
Monitoring and Profiling API
– It is now easier to observe what's going on inside the JVM
Unicode 4.0
RMI
– rmicis no longer needed to generate stubs/skeletons.
New skin for Swing
Java 5 Tiger
http://java.sun.com/j2se/1.5.0/
Complete docs
http://java.sun.com/j2se/1.5.0/docs/index.html
New (fancy) features
http://java.sun.com/j2se/1.5.0/docs/relnotes/features.html
Nice and short article about features
http://www.winplanet.com/article/2574-3801.htm
Steps To Be
readFile Followed For
{ Reading a File
in the memory
open the file;
determine its size;
allocate that much memory;
read the file into memory;
close the file;
}
Can U Guess
the potential
Errors in this
operation
Exception helps
readFile { To Solve this
catch
try { problem
(memoryAllocationFailed)
open the file; {
determine its size; doSomething;
allocate that much memory; }
read the file into memory; catch (readFailed)
close the file; {
}catch (fileOpenFailed) doSomething;
{ }
doSomething; catch (fileCloseFailed)
} {
catch(sizeDeterminationFailed) doSomething;
{ }
doSomething; }
}
96 Core Java | Muralidhar V
What is exception?
1. Built in Exceptions
Checked exceptions are so called because both the Java compiler and the
Java virtual machine check to make sure this rule is obeyed.
The checked exceptions that a method may raise are part of the method's
signature.
Every method that throws a checked exception must advertise it in the
throws clause in its method definition, and
Every method that calls a method that advertises a checked exception must
either handle that exception (with try and catch) or must in turn advertise that
exception in its own throws clause.
Object
Throwable
Error Exception
Virtual
Machine Error RuntimeException …
Exception
RuntimeException
…
(Checked Exceptions)
ArrayIndexOutOfBoundExceptio
n
(Unchecked Exceptions)
Exception
RuntimeException
…
(Checked Exceptions)
ArithmeticException
(Unchecked Exceptions)
Exception
RuntimeException
…
(Checked Exceptions)
NumberFormat
Exception
(Unchecked Exceptions)
Exception
RuntimeException
…
(Checked Exceptions)
…
NullPointerException
(Unchecked Exceptions)
Exception
RuntimeException
…
(Checked Exceptions)
…
ClassCastException
(Unchecked Exceptions)
Exception
RuntimeException
…
(Checked Exceptions)
NoSuchMethod
…
Exception
(Unchecked Exceptions)
Exception
RuntimeException
…
IOException
(Checked Exceptions)
…
(Unchecked Exceptions)
Exception
RuntimeException ClassNotFound
…
Exception
(Checked Exceptions)
…
(Unchecked Exceptions)
Occurs when the Java run time system is unable to find the
class referred.
Exception
RuntimeException IllegalAccess
…
Exception
(Checked Exceptions)
…
(Unchecked Exceptions)
Exception
RuntimeException
…
InterruptedException
(Checked Exceptions)
…
(Unchecked Exceptions)
1. try
2. catch
3. throws
4. throw
5. finally
try
{ Example
// Statements that cause an exception.
catch(ExceptionName obj)
A single try block can have zero, one or many catch blocks.
The multiple catch blocks generate unreachable code error.
If the first catch block contains the Exception class object then the
subsequent catch blocks are never executed. If this happen it is known as
unreachable code problem.
To avoid unreachable code error, the last catch block in multiple catch blocks
must contain the Exception class object.
try {
// dangerous code here!
}
Order Matters!
catch(ArithmeticException e) { Less general
// Specific error handling here first!
}
catch(RuntimeException e) {
// More general error handling here
}
try
Syntax of
{ finally block
// Block of code
}
finally
{
// Block of code that is always executed
irrespective of an exception being raised or
not.
}
122 Core Java | Muralidhar V
Try-catch-finally statement
try {
// …
} catch (ExceptionType1 identifier) {
// …
} catch (ExceptionType2 identifier) {
// …
} finally {
// …
}
The throw statement causes termination of the normal flow of control of the
Java code and stops the execution of the subsequent statements if an
exception is thrown when the throw statement is executed.
The throw clause transfers the control to the nearest catch block handling
the type of exception object throws.
throw ThrowableObj
public double divide(int dividend, int divisor) throws ArithmeticException {
if(divisor == 0) {
throw new ArithmeticException(“Divide by 0 error”);
}
return dividend / divisor;
}
124 Core Java | Muralidhar V
Using throws exceptions
Defining your own exceptions let you handle specific exceptions that are
tailor-made for your application.
Steps to Create a User Defined Exception
– Create a class that extend from a right kind of class from the
Exception Hierarchy.
– Let’s make a DivideByZeroException for use by our UnitRate class.
Here we extended
ArithmeticException.
Errors can be broadly categorized into two groups on the basis of whether the
compiler is able to handle the error or not, such as compile time errors and run
time errors.
An exception is a run time error that can be defined as an abnormal event that
occurs during the execution of a program and disrupts the normal flow of
instructions.
In Java, the Throwable class is the superclass of all the exception classes. It is
the class at the top position in the exception class hierarchy. The Exception class
and the Error class are two direct subclasses of the Throwable class.
The built-in exceptions in Java are divided into two types on the basis of the
conditions where the exception is raised:
– Checked Exceptions or Compiler-enforced Exceptions
– Unchecked exceptions or Runtime Exceptions
where Expression1 is a boolean expression. When the system runs the assertion, it
evaluates Expression1 and if it is false throws an AssertionError with no detail
message.
assert Expression1 : Expression2 ;
– Where Expression1 is a boolean expression and Expression2 is an expression that
has a value. (It cannot be an invocation of a method that is declared void.)
– This form of asssert statement provides a detail message for the AssertionError. The
system passes the value of Expression2 to the appropriate AssertionError constructor,
which uses the string representation of the value as the error's detail message.
Like all uncaught exceptions, assertion failures are generally labeled in the stack
trace with the file and line number from which they were thrown.
In order for the javac compiler to accept code containing assertions, you must
compile the code with the following
javac -source 1.4 MyClass.java
To enable assertions use -enableassertions, or -ea, option at runtime. To
disable assertions use -disableassertions, or -da. Specify the granularity with
the arguments provided at runtime.
– no arguments - Enables or disables assertions in all classes except system classes.
– packageName - Enables or disables assertions in the named package and any
subpackages.
– … - Enables or disables assertions in the unnamed package in the current working
directory.
– className - Enables or disables assertions in the named class
b. IllegalAccessException
c. InstantiationException
d. NoSuchMethodException
At the end of Day we see that you are now able to:
Define collections
Explain features of Java 1.5
Describe exceptions as well as error handling