CSE/IT 213 - Eclipse, Collections, and Exceptions: New Mexico Tech
CSE/IT 213 - Eclipse, Collections, and Exceptions: New Mexico Tech
and exceptions
New Mexico Tech
September 26, 2011
Eclipse Demo
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
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
16
Try-Catch blocks
catch runtime errors in your code
17
19
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
}
Enter an integer: &
invalid data entered
}
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
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
}
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
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
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
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
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
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
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