Collection Considerations Exceptions Testing Exceptions - PowerPoint PPT Presentation

1 / 24
About This Presentation
Title:

Collection Considerations Exceptions Testing Exceptions

Description:

Collection Class A Java language construct for encapsulating the data and operations ... Why Collection classes? ... object while it is till in the collection. ... – PowerPoint PPT presentation

Number of Views:29
Avg rating:3.0/5.0
Slides: 25
Provided by: rickmercer
Category:

less

Transcript and Presenter's Notes

Title: Collection Considerations Exceptions Testing Exceptions


1
Collection ConsiderationsExceptionsTesting
Exceptions
  • Rick Mercer

2
Some Definitions
  • Abstract Data Type (ADT) A set of data values and
    associated operations that are precisely
    specified independent of any particular
    implementation.
  • Bag, Set, List, Stack, Queue, Map
  • Collection Class A Java language construct for
    encapsulating the data and operations
  • ArrayList, LinkedList, Stack, TreeSet, HashMap
  • Data Structure An organization of information
    usually in memory
  • arrays, linked structure, binary trees, hash
    tables

3
Why Collection classes?
  • Need data structures to store data to model real
    world entities as a collection of objects
  • 3.2 billion Capitol One credit card transactions
  • Things recognized by a jet fighter's radar system
  • 35,267 students at UofA
  • All courses taken by one student
  • A set of Poker Hands
  • An appointment book
  • Phone numbers on your cell phone

4
Common Methods
  • Collection classes often have methods for
    performing operations such as these
  • Adding an object to the collection of objects
  • Removing an object from the collection
  • Getting a reference to a particular object find
  • then you can send messages to the object while it
    is till in the collection. Program do this a lot
  • Retrieving certain objects such as the most
    recently pushed (Stack) or least recently
    enqueued (Queue)
  • Arranging objects in a certain order sorting

5
Storage Mechanisms
  • We have used a 1-D array for storage
  • elements in a set
  • We have used a 2-D array for storage
  • represent a society of cells in Artificial Life
  • Can have linked structures to store elements
  • Elements are not located in contiguous (next to
    each other) memory as with arrays

6
Structures to store elements
  • Collection classes can store data in contiguous
    memory (arrays)
  • or in a linked structure (linked lists, trees)

2 8 9 11 14 14 22 24 27 31
7
- or in tree structures
50
75
25
12
35
66
90
28
41
81
95
54
91
100
8
- or in hash tables
  • Maps associate a key with a value
  • Elements could be stored in a hash table

9
The List ADT
  • Dictionary Definition of a List
  • list n. A series of names, words, or other items
    written, printed, or imagined one after the
    other a shopping list a guest list a list of
    things to do.
  • Abstract?
  • Is this a list?
  •  

10
A C Sc definition of List
  • List
  • an ordered sequence of elements
  • has a first element, a second element, and an
    element that is at the end of the list
  • could be empty have zero elements
  • provides access to elements at any location
  • Elements are found, added, and removed using an
    integer index that represents the relative
    position of the element in the list

11
List as an array structure
  • Can use an array as the data structure
  • Elements are stored in contiguous (next to each
    other) memory
  • Each array element stores a primitive value or a
    reference to an object

12
List as a linked structure
  • A linked structure provides an alternative
    implementation of collection classes
  • "Linked" structures are a collection of nodes
  • Each node stores a reference to an object and a
    reference to another node
  • first references the linked structure
  • The last element references nothing (we'll use
    null)

13
Sequential processing, not direct access like
arrays
  • Linked structures store a collection sequentially
  • Start at the beginning to find anything
  • Each element has a successor and predecessor
  • except the first and last element
  • The collection of nodes has each storing
  • a reference to some value it will be called data
  • a reference to another node it will be called
    next
  • Maintains memory on an as needed basis

14
Generics
  • Java 5 has generics
  • Allows one class to store collections of any type
  • You implemented the generic bag class
  • see project 6

15
Java's Exception Hierarchy
  • Exceptions handle weird and awkward things
  • Some are standard exceptions that must be
  • caught with try and catch blocks,
  • or declared to be thrown in every method
  • The read message wont compile unless you do one
    or the other
  • public static void main(String a) throws
    IOException
  • try
  • System.in.read()
  • catch(IOException e)
  • System.out.println("read went wrong")

16
Exceptions
  • When programs run, errors occur
  • Examples of "exceptional events" include
  • Division by 0
  • Attempt to open a file that does not exist
  • Array subscript out of bounds
  • Trying to convert a string from a text field to a
    number and the string is not a valid number
  • When programs run, exceptions occur
  • can handle them (see next slide)

17
Handling exceptional events
  • Put code that "throws" exceptional event into a
    try block
  • try
  • code that throw may throw an
    exception
  • catch (Exception anException)
  • code that executes when an exception is
    thrown
  • If that code "throws" an Exception, the code in
    the catch block executes

18
Example
  • ParseDouble may be passed a string that does not
    represent a valid number
  • String numberAsString depositField.getText()
  • double amount 0.0
  • try
  • amount Double.parseDouble(numberAsString)
  • catch(NumberFormatException nfe)
  • JOptionPane.showMessageDialog(null,
  • "Invalid deposit "
    numberAsString) depositField.setText("")

19
API Documentation
  • public static double parseDouble(String s)
  • throws NumberFormatException
  • Returns a new double initialized to the value
    represented by the specified String, as performed
    by the valueOf method of class Double.
  • Parameters s - the string to be parsed.
  • Returns the double value represented by the
    string argument.
  • Throws NumberFormatException - if the string
    does not contain a parsable double.
  • Many methods throw an exception
  • Your methods could also

20
Part of the Throwable
inheritance hierarchy
Object
Throwable
The arrows are UML notation for the inheritance
relationship between classes
Exception
Error
IOException
RunTimeException
FileNotFoundException
NullPointerException
IndexOutOfBoundsException
EOFException
ArrayIndexOutOfBoundsException
21
Base and derived classes
  • Object is the super class of all classes
  • The Throwable class is the superclass of all
    errors and exceptions in the Java language
  • Error indicates serious problems that a
    reasonable application should not try to catch.
  • Exception and its subclasses are a form of
    Throwable that indicates conditions that a
    reasonable application might want to catch

22
Java's Throwable hierarchy is wide and deep (many)
  • See http//java.sun.com/j2se/1.4.2/docs/api/java/l
    ang/Exception.html
  • RuntimeException is the superclass of exceptions
    that can be thrown during the normal operation of
    the Java Virtual Machine
  • IOException classes are related to I/O
  • IndexOutOfBounds exceptions indicate that an
    index of some sort (such as to an array, to a
    string, or to an ArrayList) that is out of range

23
Our Methods must throw an Exception
  • Consider an illegal argument, such as a negative
    withdrawal amount
  • public void withdraw(double amt)
  • if(amt lt 0.0)
  • throw new IllegalArgumentException()
  • //

24
Test that the method does in fact throw an
exception
  • public void testThatTheMethodDoesThrowException()
  • BankAccount anAcct new BankAccount("Sam, 12)
  • try
  • anAcct.withdraw(-1.00)
  • fail() // only if exception is NOT thrown
  • catch (IllegalArgumentException iae)
  • // If the method is thrown nothing happens
  • Note In non-test code, you are not required to
    try a method that extends RunTimeException (but
    you may)
Write a Comment
User Comments (0)
About PowerShow.com