You are on page 1of 58

CSE/IT 213 - Eclipse, collections,

and exceptions
New Mexico Tech
September 26, 2011

Eclipse Demo

Collections Class Hierarchy


Ellipse - Interface
dashed boxes - Abstract Classes
solid box - Concrete Class
solid line - extends
dashed line - implements

Interfaces
Iterators - Want to be able to sequence through the
items of a collection.
public interface Iterable<T>
from javadoc Implementing this interface allows an
object to be the target of the foreach statement.
Collection - A group or set of similar object or data.
May or may not be ordered. Data may or may not be
indexed, i.e.key-value pairs.
What is the first object of a change jar? A button jar?
A junk drawer?
3

Example. Arrays are a collection. Can iterate through


an array by using its index.
public interface Collection<E> extends Iterable<E>
from javadoc The root interface in the collection hierarchy. A collection represents a group of objects,
known as its elements. Some collections allow duplicate elements and others do not. Some are ordered
and others unordered. The JDK does not provide any
direct implementations of this interface: it provides implementations of more specific subinterfaces like Set
and List. This interface is typically used to pass collections around and manipulate them where maximum
generality is desired.

List - a sequence of items. Items may be repeated.


There is first item, a last item, and a n-th item.
public interface List<E> extends Collection<E>
from javadoc An ordered collection (also known as
a sequence). The user of this interface has precise
control over where in the list each element is inserted.
The user can access elements by their integer index
(position in the list), and search for elements in the
list.

Set - like the mathematical set no duplicates, unordered.


public interface Set<E> extends Collection<E>
From javadoc A collection that contains no duplicate
elements. More formally, sets contain no pair of elements e1 and e2 such that e1.equals(e2), and at most
one null element. As implied by its name, this interface
models the mathematical set abstraction.

SortedSet
public interface SortedSet<E> extends Set<E>
From javadoc A Set that further provides a total ordering on its elements. The elements are ordered using their natural ordering, or by a Comparator typically
provided at sorted set creation time. The sets iterator
will traverse the set in ascending element order. Several
additional operations are provided to take advantage of
the ordering.

Abstract Classes
Abstract Collection
public abstract class AbstractCollection<E>
extends Object
implements Collection<E>
From javadoc This class provides a skeletal implementation of the Collection interface, to minimize the effort
required to implement this interface.

AbstractList
public abstract class AbstractList<E>
extends AbstractCollection<E>
implements List<E>
From javadoc This class provides a skeletal implementation of the List interface to minimize the effort required to implement this interface backed by a random
access data store (such as an array). For sequential
access data (such as a linked list), AbstractSequentialList should be used in preference to this class.

AbstractSet
public abstract class AbstractSet<E>
extends AbstractCollection<E>
implements Set<E>
From javadoc This class provides a skeletal implementation of the Set interface to minimize the effort required to implement this interface.

AbstractSequentialList
public abstract class AbstractSequentialList<E>
extends AbstractList<E>
from javadoc This class provides a skeletal implementation of the List interface to minimize the effort required to implement this interface backed by a sequential access data store (such as a linked list). For
random access data (such as an array), AbstractList
should be used in preference to this class.

Concrete Classes
LinkedList
public class LinkedList<E>
extends AbstractSequentialList<E>
implements List<E>, Deque<E>, Cloneable, Serializable
from javadoc 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.
10

ArrayList
public class ArrayList<E>
extends AbstractList<E>
implements List<E>, RandomAccess, Cloneable, Serializable
from javadoc 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.)
11

Vector
public class Vector<E>
extends AbstractList<E>
implements List<E>, RandomAccess, Cloneable, Serializable
from javadoc The Vector class implements a growable
array of objects. Like an array, it contains components
that can be accessed using an integer index. However, the size of a Vector can grow or shrink as needed
to accommodate adding and removing items after the
Vector has been created....Unlike the new collection implementations, Vector is synchronized.
12

Stack
public class Stack<E>
extends Vector<E>
from javadoc The Stack class represents a last-in-firstout (LIFO) stack of objects. It extends class Vector
with five operations that allow a vector to be treated
as a stack. The usual push and pop operations are
provided, as well as a method to peek at the top item
on the stack, a method to test for whether the stack is
empty, and a method to search the stack for an item
and discover how far it is from the top.
13

HashSet
public class HashSet<E>
extends AbstractSet<E>
implements Set<E>, Cloneable, Serializable
from javadoc 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.

14

TreeSet
public class TreeSet<E>
extends AbstractSet<E>
implements NavigableSet<E>, Cloneable, Serializable
from javadoc A NavigableSet implementation based
on a TreeMap [a red-black tree]. The elements are
ordered using their natural ordering, or by a Comparator provided at set creation time, depending on which
constructor is used.

15

Exceptions Handling Errors in


Java
Two types
assertions catch logical errors in your code
exceptions run time errors

16

Try-Catch blocks
catch runtime errors in your code

17

Some simple code ....


import java.util.*;
public class Junk {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
System.out.print("Enter an integer: ");
int i = in.nextInt();
System.out.println("You entered " + i);
}
}
Enter an integer: 7
You entered 7
18

What happens if you dont enter an integer.


Get a runtime error
Enter an integer: ^
Exception in thread "main" java.util.InputMismatchException
at java.util.Scanner.throwFor(Scanner.java:840)
at java.util.Scanner.next(Scanner.java:1461)
at java.util.Scanner.nextInt(Scanner.java:2091)
at java.util.Scanner.nextInt(Scanner.java:2050)
at Junk.main(Junk.java:7)

19

You threw an exception


You need to catch the exception to effectively deal with
it.
Where do you find the exceptions? Javadoc
The method section of documentation show what the
method will throw.
For Scanner.nextInt()
Throws
InputMismatchException if the next token does not match the
Integer regular expression, or is out of range
NoSuchElementException - if input is exhausted
IllegalStateException - if this scanner is closed
20

try-catch blocks
try block - a block of code that will throw an exception
catch block - a block of code that will catch the
exception thrown by the try block. Only executes if
the try block throws an exception

21

A better way to read in input


import java.util.*;
public class Junk {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
System.out.print("Enter an integer: ");
try {
int i = in.nextInt();
System.out.println("You entered " + i);
}
catch (InputMismatchException e) {
System.out.println("invalid data entered");
}
}
22

}
Enter an integer: &
invalid data entered

Captured error, but program didnt capture data.


To make program work as expected use a while loop
import java.util.*;
public class Junk {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
boolean data = true;
while(data) {
System.out.print("Enter an integer: ");
try {
int i = in.nextInt();
System.out.println("You entered " + i);
data = false;
23

}
catch (InputMismatchException e) {
in.next(); //w/o it infinie loop
//clears out input buffer
System.out.println("invalid data entered");
}
}
}
}
Enter an integer: *
invalid data entered
Enter an integer: 5
You entered 5

Exceptions are instances of the class Throwable


Throwable has two subclasses -Error and Exception
Error dont catch these...these kill the program at
run-time or as javadoc says An Error is a subclass
of Throwable that indicates serious problems that a
reasonable application should not try to catch. Most
such errors are abnormal conditions.
Exception catch these ...or as javadoc says a form of
Throwable that indicates conditions that a reasonable
application might want to catch.
Keyword might
24

Do not need to catch all exceptions


Exception has some useful utility methods getMessage()
and printStackTrace()

import java.util.*;
public class Junk {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
boolean data = true;
while(data) {
System.out.print("Enter an integer: ");
try {
int i = in.nextInt();
System.out.println("You entered " + i);
data = false;
}
catch (InputMismatchException e) {
in.next();
System.out.println(e.getMessage());
25

e.printStackTrace();
}
}
}
}
Enter an integer: &
null //e.getMessage()
Enter an integer: java.util.InputMismatchException
at java.util.Scanner.throwFor(Scanner.java:840)
at java.util.Scanner.next(Scanner.java:1461)
at java.util.Scanner.nextInt(Scanner.java:2091)
at java.util.Scanner.nextInt(Scanner.java:2050)
at Junk.main(Junk.java:12)
Enter an integer: 5
You entered 5

Can write your own exceptions


import java.util.*;
public class Junk {
public static void main(String[] args) throws Exception {
Scanner in = new Scanner(System.in);
System.out.print("enter an integer: ");
try {
int i = in.nextInt();
if (i < 0)
throw new Exception("i has to be >= 0");
System.out.println("Square root of " + i + " is "
+ Math.sqrt(i));
26

}
catch (InputMismatchException e) {
in.next(); //w/o this infinite loop
System.out.println(e.getMessage());
e.printStackTrace();
}
catch (Exception e) {
System.out.println(e.getMessage());
}
}
}
enter an integer: -1
i has to be >= 0

Only one of the catch blocks execute. First one that


handle the exception.
Order matters put your specific exceptions before the
catch all, (catch Exception e). The catch all behaves
a lot like the default statement in switch.
Better to be specific with exceptions you catch.

27

finally block
Can add a finally block at end of try-catch blocks.
Put clean-up code, etc.
finally blocks always execute, no matter what.

28

import java.util.*;
public class Junk {
public static void main(String[] args) throws Exception {
Scanner in = new Scanner(System.in);
System.out.print("enter an integer: ");
try {
int i = in.nextInt();
if (i < 0)
throw new Exception("i has to be >= 0");
System.out.println("Square root of " + i + " is "
+ Math.sqrt(i));
return;
}
29

catch (InputMismatchException e) {
in.next(); //w/o this infinite loop
System.out.println(e.getMessage());
e.printStackTrace();
}
catch (Exception e) {
System.out.println(e.getMessage());
}
finally {
System.out.println("goodbye...");
}
}
}

enter an integer: 6
Square root of 6 is 2.449489742783178
goodbye...

Exceptions Bubble Up
What happens when there is no matching exception in
try-catch block? Where does the exception go?
Say you call a method, and the method throws an exception. If the method cant handle the exception, it
returns the exception to the method that called it. If
the caller can deal with exception, say the method was
called from a try-catch block, it tries to handle the
exception. Otherwise it throws the exception up the
call stack, looking for a method that can catch the exception. If no method can handle the exception, the
exception results in a run-time error, and the program
terminates.
30

For this to work, methods need to declare that they


can throw an exception.
void method name throws Exception
Lots of subclases of Exception so can throw those as
well, and can have a multiple exceptions thrown, which
you put in a comma separated list.
void getData() throws IOException, InstantiationException{...}
See javadoc for description and names of subclasses of
Exceptions.
If a method or class imposes some exceptions, it is the
responsibility of the method or class to deal with it. So
propagate exceptions back to method that imposed the
restriction.

Constructors and exceptions


Constructors can throw exceptions
You can use try-catch blocks in constructors, but this
will disallow the use of this in constructors as it needs
to be the first line of a constructor.

31

Exception Types
Checked vs. Unchecked
The type of exception a method throws is called a
checked exception. Checked exceptions, problems the
program can recover from.
Checked exceptions must be handled by the caller of
the method.
Two ways method uses try-catch block, or it itself
throws the exception and lets some other method deal
with it.
Unchecked excpetions serious issues cant recover
from. Not caught.
32

Defining your own Exceptions


Exceptions is a class, so can extend it to create own
exception classes.
public class PointException extends Exception {
PointException() {
super(); //calls Exception()
}
PointException(Sting msg) {
super(msg); //calls Exception(String message)
}
}
33

Then can use exception in try-catch blocks


....
try {
...
}
catch (PointException pe) {
...
}

34

Chaining Exceptions
You catch an exception and process the exception, but
want to throw a new exception as well.
For example, you might catch an IOException dealing
with a file. Catch block can process but want to be
more user friendly to the user of program
One way, just throw a new exception. If you do, lose
what caused the exception.
Better way, use constructor public Exception(String message,
Throwable cause)
35

The cause is what triggered the exception in the first


place, and the message is the new message for you new
exception.
To get the stack Trace and other info of the cause, you
use the Throwable Exception.getCause() method.
This is called chaining exceptions.

Assertions
An assertion is a simple pass-fail test of some condition,
performed while application runs.
Sanity check of code
Can be turned on and off at runtime using java -ea
Application
A way to test software as you build it. Used for quality
control of software.
Program exits on assertion errors
36

Assertion example 1
public class MySqrt {
public double getSqrt(double d) {
//pre: d >= 0
assert d >= 0;
return Math.sqrt(d);
}
}
import java.util.*;
public class Junk {
public static void main(String[] args) throws Exception {
37

double d;
MySqrt mysqrt = new MySqrt();
d = mysqrt.getSqrt(-1.7);
System.out.println(d);
}
}
Exception in thread "main" java.lang.AssertionError
at MySqrt.getSqrt(MySqrt.java:6)
at Junk.main(Junk.java:7)

Assertion Example 2
public class MySqrt {
public double getSqrt(double d) {
//pre: d >= 0
assert d >= 0: "less than zero";
return Math.sqrt(d);
}
}
import java.util.*;
public class Junk {
public static void main(String[] args) {
38

double d;
MySqrt mysqrt = new MySqrt();
d = mysqrt.getSqrt(-1.7);
System.out.println(d);
}
}
Exception in thread "main"
java.lang.AssertionError: less than zero
at MySqrt.getSqrt(MySqrt.java:6)
at Junk.main(Junk.java:7)

Assertion Syntax
assert <condition> :
The :

<expression>

<expression> is optional

Expressions can use concatenation:


assert d >= 0 : d + " less than zero";
produces
java.lang.AssertionError:

-1.7 less than zero

39

Types of Assertions
pre- and post condition assertions
pre-condition check the validity of input to method.
Typically, assertions are not used for pre-conditions.
Better to use Exception handling, particularly for public
methods.
Want pre-condition checks to be part of your code, not
software QA.
Exception private methods use assertions.
40

public class MySqrt {


public double getSqrt(double d) throws Exception {

if (d <= 0)
throw new Exception("Input less than Zero");
return Math.sqrt(d);
}
}
import java.util.*;
public class Junk {
public static void main(String[] args) {
41

double d;
MySqrt mysqrt = new MySqrt();
try {
d = mysqrt.getSqrt(-1.7);
System.out.println(d);
}
catch (Exception e) {
System.out.println(e.getMessage());
}
}
}
Input less than Zero

Post-condtions
Checking the results of your methods before returning
them, a good idea. These are called post-conditions.
public class MySqrt {
public double getSqrt(double d) {
Double
answer
assert
return

answer; //autoboxing
= Math.sqrt(d);
!answer.isNaN() : "not a number";
answer;

}
}
42

import java.util.*;
public class Junk {
public static void main(String[] args) {
double d;
MySqrt mysqrt = new MySqrt();
d = mysqrt.getSqrt(-1.7);
System.out.println(d);
}
}
Exception in thread "main"
java.lang.AssertionError:

not a number

You might also like