Peter Andreae Engineering and Computer Science Victoria University of Wellington Copyright: Peter Andreae, Victoria University of Wellington2012 Implementing.

Slides:



Advertisements
Similar presentations
Chapter 17 Failures and exceptions. This chapter discusses n Failure. n The meaning of system failure. n Causes of failure. n Handling failure. n Exception.
Advertisements

COMP 121 Week 9: AbstractList and ArrayList. Objectives List common operations and properties of Lists as distinct from Collections Extend the AbstractCollection.
CMSC 132: Object-Oriented Programming II Nelson Padua-Perez William Pugh Department of Computer Science University of Maryland, College Park.
Lecture 23 Input and output with files –(Sections 2.13, 8.7, 8.8) Exceptions and exception handling –(Chapter 17)
HST 952 Computing for Biomedical Scientists Lecture 7.
CSC 205 – Java Programming II Lecture 25 March 8, 2002.
Java Programming Exceptions. Java has a built in mechanism for error handling and trapping errors Usually this means dealing with abnormal events or code.
COMP201 Java Programming Topic 6: Exceptions Reading: Chapter 11.
CSE 143 Lecture 22: Advanced List Implementation (ADTs; interfaces; abstract classes; inner classes; generics; iterators)
Java Collections Framework COMP53 Oct 24, Collections Framework A unified architecture for representing and manipulating collections Allows collections.
15-Jun-15 Lists in Java Part of the Collections Framework.
Exceptions in Java Fawzi Emad Chau-Wen Tseng Department of Computer Science University of Maryland, College Park.
CHAPTER 6 Stacks Array Implementation. 2 Stacks A stack is a linear collection whose elements are added and removed from one end The last element to be.
Unit 291 Java Collections Framework: Interfaces Introduction to the Java Collections Framework (JCF) The Comparator Interface Revisited The Collection.
Lists in Java Part of the Collections Framework. Kinds of Collections Collection --a group of objects, called elements –Set-- An unordered collection.
12-Jul-15 Lists in Java Part of the Collections Framework.
CS 106 Introduction to Computer Science I 04 / 30 / 2010 Instructor: Michael Eckmann.
Java Exception Handling
Exceptions. Many problems in code are handled when the code is compiled, but not all Some are impossible to catch before the program is run  Must run.
COMP 103 Comparators and Comparable. RECAP  Iterator and Iterable TODAY  Comparator and Comparable  Exceptions 2 RECAP-TODAY.
Programming in C++ 1. Learning Outcome  At the end of this slide, student able to:  Understand what is Inheritance?  Compare between inheritance and.
Exception Handling Exceptions and language features to handle them.
Programming in C++ 1. Learning Outcome At the end of this slide, student able to:  Identify the different types of error in your program  Understand.
Peter Andreae Computer Science Victoria University of Wellington Copyright: Peter Andreae, Victoria University of Wellington Summary and Exam COMP 102.
Data Structures and Abstract Data Types "Get your data structures correct first, and the rest of the program will write itself." - David Jones.
Collections in Java. Kinds of Collections Collection --a group of objects, called elements –Set-- An unordered collection with no duplicates SortedSet.
JAVA COLLECTIONS LIBRARY School of Engineering and Computer Science, Victoria University of Wellington COMP T2, Lecture 2 Marcus Frean.
Peter Andreae Computer Science Victoria University of Wellington Copyright: Peter Andreae, Victoria University of Wellington ArraySet and Binary Search.
CSE 143 Lecture 4 ArrayList Reading: 10.1 slides created by Marty Stepp
IMPLEMENTING ARRAYLIST – Part 2 COMP 103. RECAP  Abstract Classes – overview, details in 2 nd year  Implementing the ArrayList: size(), get(), set()
Some Other Collections: Bags, Sets, Queues and Maps COMP T2 Lecture 4 School of Engineering and Computer Science, Victoria University of Wellington.
Data Design and Implementation. Definitions of Java TYPES Atomic or primitive type A data type whose elements are single, non-decomposable data items.
30 May Stacks (5.1) CSE 2011 Winter Stacks2 Abstract Data Types (ADTs) An abstract data type (ADT) is an abstraction of a data structure An.
1/20/03A2-1 CS494 Interfaces and Collection in Java.
Collections in Java. 2 Collections Hierarchy > ArrayListVector Stack LinkedList > Arrays Collections.
(c) University of Washington15-1 CSC 143 Java List Implementation via Arrays Reading: 13.
2014-T2 Lecture 19 School of Engineering and Computer Science, Victoria University of Wellington  Marcus Frean, Lindsay Groves, Peter Andreae, and John.
1 Collection, Iterable, and Iterator Interfaces The Collection Interface and its Hierarchy The Iterable and Iterator Interfaces For-each Loops with Iterable.
CSC 212 – Data Structures Lecture 17: Stacks. Question of the Day Move one matchstick to produce a square.
2013-T2 Lecture 18 School of Engineering and Computer Science, Victoria University of Wellington  Marcus Frean, Lindsay Groves, Peter Andreae, and John.
Interfaces, Classes, Collections School of Engineering and Computer Science, Victoria University of Wellington COMP T2 Lecture 3 Thomas Kuehne.
(c) University of Washington16-1 CSC 143 Java Lists via Links Reading: Ch. 23.
CMSC 132: Object-Oriented Programming II Java Constructs Department of Computer Science University of Maryland, College Park.
This recitation 1 An interesting point about A3: Using previous methods to avoid work in programming and debugging. How much time did you spend writing.
 In the java programming language, a keyword is one of 50 reserved words which have a predefined meaning in the language; because of this,
© 2006 Pearson Addison-Wesley. All rights reserved5 B-1 Chapter 5 (continued) Linked Lists.
Peter Andreae Computer Science Victoria University of Wellington Copyright: Peter Andreae, Victoria University of Wellington Types and Interfaces COMP.
Recitation 5 Enums and The Java Collections classes/interfaces 1.
JAVA COLLECTIONS LIBRARY School of Engineering and Computer Science, Victoria University of Wellington COMP T2, Lecture 2 Thomas Kuehne.
Peter Andreae Computer Science Victoria University of Wellington Copyright: Peter Andreae, Victoria University of Wellington Summary and Exam COMP 102.
Copyright © Curt Hill Error Handling in Java Throwing and catching exceptions.
IMPLEMENTING ARRAYLIST COMP 103. RECAP  Comparator and Comparable  Brief look at Exceptions TODAY  Abstract Classes - but note that the details are.
Interfaces, Classes, Collections School of Engineering and Computer Science, Victoria University of Wellington COMP T2 Lecture 3 Marcus Frean.
JAVA COLLECTIONS LIBRARY School of Engineering and Computer Science, Victoria University of Wellington COMP T2, Lecture 2 Marcus Frean.
(c) University of Washington10-1 CSC 143 Java Errors and Exceptions Reading: Ch. 15.
2015-T2 Lecture 19 School of Engineering and Computer Science, Victoria University of Wellington  Marcus Frean, Lindsay Groves, Peter Andreae, and John.
M180: Data Structures & Algorithms in Java Stacks Arab Open University 1.
Implementing ArrayList Part T2 Lecture 6 School of Engineering and Computer Science, Victoria University of Wellington  Thomas Kuehne, Marcus Frean,
Exceptions and Error Handling. Exceptions Errors that occur during program execution We should try to ‘gracefully’ deal with the error Not like this.
Garbage Collection It Is A Way To Destroy The Unused Objects. To do so, we were using free() function in C language and delete() in C++. But, in java it.
1 Stacks Abstract Data Types (ADTs) Stacks Application to the analysis of a time series Java implementation of a stack Interfaces and exceptions.
 2016, Marcus Biel, ArrayList Marcus Biel, Software Craftsman
Using the Java Collection Libraries COMP 103 # T2
Implementing ArrayList Part 1
Preconditions precondition: Something your method assumes is true at the start of its execution. Often documented as a comment on the method's header:
ArrayLists 22-Feb-19.
Collections Framework
Coming up Exceptions An Example The Throws keyword Try and Catch
Part of the Collections Framework
Arrays and ArrayLists.
Presentation transcript:

Peter Andreae Engineering and Computer Science Victoria University of Wellington Copyright: Peter Andreae, Victoria University of Wellington2012 Implementing Collections COMP 103 # Tri 2

COMP103 7:2 Menu Exceptions Implementing Collections: Interfaces, Abstract Classes, Classes Notes: Assignment 3 out. Molecule Renderer (Comparators, Lists, Maps) Undo for Sokoban (Stacks) updated UI Assig 2: concurrency!!!! Forum broke in weekend.

COMP103 7:3 Other actions on Collections Shuffle, Rotate, Reverse Apply to Lists only Static methods in Collections class Collections.shuffle(hand); Collections.reverse(hand); Collections.rotate(hand, 3); // moves every element of list forward 3 steps, wrapping around at the end of the list. Fill, Max, Min, swap, asList Collections.fill(hand, new Card(1, "hearts")); double m = Collections.Max(myNumbers); // any collection Collections.swap(hand, 4, 8); List suits = Arrays.asList("hearts", "diamonds", "clubs", "spades"); // fixed length list of values. asList can have any number of arguments!

COMP103 7:4 Exceptions What should a method do when something goes wrong? Throw an exception! An Exception is a “non-local exit” Error of some kind, eg file doesn’t exist, dividing by zero calling a method on the null object calling an undefined method An exceptional situation, eg text in file file doesn’t have the expected format user enters an unexpected answer How do you deal with Exceptions? handling (catching) exceptions throwing exceptions May be thrown by the JVM when executing code. May be thrown by code from the java library May be deliberately thrown by your code.

COMP103 7:5 Catching exceptions exceptions thrown in a try... catch can be “caught”: try { … code that might throw an exception } catch ( 〈 ExceptionType1 〉 e1) { …actions to do in this case….} catch ( 〈 ExceptionType2 〉 e2) { …actions to do in this case….} catch ( 〈 ExceptionType3 〉 e3) { …actions to do in this case….} Meaning: If an exception is thrown, jump to catch clauses, Match exception type against each catch clause If caught, perform the actions, and jump to code after all the catch clauses The actions may use information in the exception object. Exception object, containing information about the state System.out.println(e.getMessage()); e.printStackTrace(); } Informative action for an error condition that the program can’t deal with itself

COMP103 7:6 Types of Exceptions Lots of kinds of exceptions Exceptions AclNotFoundException, ActivationException, AlreadyBoundException, ApplicationException, AWTException, BackingStoreException, BadAttributeValueExpException, BadBinaryOpValueExpException, BadLocationException, BadStringOperationException, BrokenBarrierException, CertificateException, ClassNotFoundException, CloneNotSupportedException, DataFormatException, DatatypeConfigurationException, DestroyFailedException, ExecutionException, ExpandVetoException, FontFormatException, GeneralSecurityException, GSSException, IllegalAccessException, IllegalClassFormatException, InstantiationException, InterruptedException, IntrospectionException, InvalidApplicationException, InvalidMidiDataException, InvalidPreferencesFormatException, InvalidTargetObjectTypeException, InvocationTargetException, IOException, JMException, LastOwnerException, LineUnavailableException, MidiUnavailableException, MimeTypeParseException, NamingException, NoninvertibleTransformException, NoSuchFieldException, NoSuchMethodException, NotBoundException, NotOwnerException, ParseException, ParserConfigurationException, PrinterException, PrintException, PrivilegedActionException, PropertyVetoException, RefreshFailedException, RemarshalException, RuntimeException, SAXException, ServerNotActiveException, SQLException, TimeoutException, TooManyListenersException, TransformerException, UnmodifiableClassException, UnsupportedAudioFileException, UnsupportedCallbackException, UnsupportedFlavorException, UnsupportedLookAndFeelException, URISyntaxException, UserException, XAException, XMLParseException, XPathException RunTimeExceptions: AnnotationTypeMismatchException, ArithmeticException, ArrayStoreException, BufferOverflowException, BufferUnderflowException, CannotRedoException, CannotUndoException, ClassCastException, CMMException, ConcurrentModificationException, DOMException, EmptyStackException, EnumConstantNotPresentException, EventException, IllegalArgumentException, IllegalMonitorStateException, IllegalPathStateException, IllegalStateException, ImagingOpException, IncompleteAnnotationException, IndexOutOfBoundsException, JMRuntimeException, LSException, MalformedParameterizedTypeException, MissingResourceException, NegativeArraySizeException, NoSuchElementException, NullPointerException, ProfileDataException, ProviderException, RasterFormatException, RejectedExecutionException, SecurityException, SystemException, TypeNotPresentException, UndeclaredThrowableException, UnmodifiableSetException, UnsupportedOperationException

COMP103 7:7 Types of Exceptions Lots of kinds of exceptions RuntimeExceptions don’t have to be handled: An uncaught RuntimeException will result in an error message You can catch them if you want. Other Exceptions must be handled: Either explicitly caught, or the method must declare that it might throw that kind of exception. eg IOException (which is why we always used a try…catch when opening files). An exception object contains information: the state of the execution stack any additional information specific to the exception

COMP103 7:8 Throwing exceptions The throw statement causes an exception. eg, a drawing file has a line with an unknown shape: if (name.equals("oval"))shapes.add(new Oval(file)); else if (name.equals("rectangle"))shapes.add(new Rectangle(file)); else if (name.equals("line"))shapes.add(new Line(file)); : else if (name.equals("polyline"))shapes.add(new PolyLine(file)); else throw new RuntimeException(“Unknown shape in drawing file”); render(); eg, defining a method that shouldn’t be called such as adding an element to an immutable List public void add(E element){ throws new UnsupportedOperationException(“Immutable List”); } General RuntimeException object. Could use a more specific one Could define our own exception

COMP103 7:9 Implementing Collections Part 1: using collections Different types of collections The Java collections library Interfaces for List, Set, Map, Stack, Queue Using “for each” loop, Iterable, and Iterators Using Sort, Comparable, and Comparators Throwing exceptions Part 2: implementing collections What it means to implement a Collection Interface Alternative data structures and algorithms Cost and efficiency Testing Binary search algorithm Sorting algorithms ✔ ✔ ✔ ✔ ✔ ✔

COMP103 7:10 Interfaces and Classes Interface Specifies type defines method headers only Class implements Interface defines fields for the data structures to hold the data. defines method bodies defines constructors List Specifies sequence of E size, add 1, get, set, remove 1 add 2, addAll, addAll, clear, contains, containsAll, equals, hashCode, isEmpty, indexOf, lastIndexOf, iterator, listIterator, remove 2, removeAll,retainAll, subList, toArray. ArrayList implements List defines fields with array of and count defines size(), add( … defines … defines constructors

COMP103 7:11 Defining List: Type Variables public interface List extends Collection { public int size (); public E get (int index); public E set (int index, E elem); public boolean add (E elem); public boolean add (int index, E elem); public E remove (int index); public void remove (Object ob); public Iterator iterator(); public void clear(); public boolean contains (Object ob); public int indexOf (Object ob); public boolean addAll (Collection c); : E is a type variable E will be bound to an actual type when a list is declared: private List items;

COMP103 7:12 “Generics” and Type variables Declaring a variable/field holding a List: Must specify the type of the elements in the List private List drawing; Constructing a List object: Must specify the type of the elements in the List crowd = new List (); Defining the List interface, or the ArrayList class: We are defining every kind of List We use a type variable to stand for whatever element type is specified in declaration or constructor. public interface List extends Collection { E will be bound to a real type when a List is declared or constructed.

COMP103 7:13 Defining ArrayList Design the data structures to store the values array of items count Define the fields and constructors public class ArrayList implements List { private E [ ] data; private int count; Define all the methods specified in the List interface size()add(E o)add(int index, E element)contains(Object o)get(int index) isEmpty()clear()set(int index, E element)indexOf(Object o)remove(int index) remove(Object o)lastIndexOf(Object o)iterator() equals(Object o) hashCode()listIterator() listIterator(int index) addAll(Collection c)addAll(int index, Collection c) containsAll(Collection c)removeAll(Collection c)toArray() subList(int fromIndex, int toIndex) retainAll(Collection c)toArray(T[] a)

COMP103 7:14 Defining ArrayList Design the data structures to store the values array of items count Define the fields and constructors public class ArrayList implements List { private E [ ] data; private int count; Define all the methods specified in the List interface size()add(E o)add(int index, E element)contains(Object o)get(int index) isEmpty()clear()set(int index, E element)indexOf(Object o)remove(int index) remove(Object o)lastIndexOf(Object o)iterator() equals(Object o) hashCode()listIterator() listIterator(int index) addAll(Collection c)addAll(int index, Collection c) containsAll(Collection c)removeAll(Collection c)toArray() subList(int fromIndex, int toIndex) retainAll(Collection c)toArray(T[] a)

COMP103 7:15 Defining ArrayList: too many methods Problem: There are a lot of methods in List that need to be defined in ArrayList, and many are complicated. But, many could be defined in terms of a few basic methods: (size, add, get, set, remove) eg, public boolean addAll(Collection other){ for (E item : other) add(item); } Solution: An Abstract class Defines the complex methods in terms of the basic methods Leaves the basic methods “abstract” (no body) classes implementing List can extend the abstract class.

COMP103 7:16 Interfaces and Classes Interface Specifies type defines method headers Abstract Class implements Interface defines some methods leaves other methods “abstract” Class extends Abstract Class defines data structures defines basic methods defines constructors List Specifies sequence of etype AbstractList implements List defines array of defines addAll, subList, … add, set, get, … left abstract ArrayList extends AbstractList implements fields & constructor implements add, get, …

COMP103 7:17 AbstractList public abstract class AbstractList implements List { public abstract int size(); public boolean isEmpty(){ return (size() == 0); } public abstract E get(int index); public void add(int index, E element){ throws new UnsupportedOperationException(); } public boolean add(E element){ add(size(), element); declared abstract - must be defined in a real class defined in terms of size() declared abstract - must be defined in a real class defined to throw exception should be defined in real class defined in terms of other add No constructor or fields

COMP103 7:18 AbstractList continued public boolean contains(Object ob){ for (int i = 0; i<size(); i++) if (get(i).equals(ob) ) return true; return false; } public void clear(){ while (size() > 0) remove(0); } : AbstractList cannot be instantiated. defined in terms of size and get defined in terms of size and remove

COMP103 7:19 ArrayList extends AbstractList public class ArrayList extends AbstractList { // fields to hold the data: need an array for the items and an int for the count. // constructor(s) Initialise the array // definitions of basic methods not defined in AbstractList size() get(index) set(index, value) add(index, value) remove(index) iterator() // (other methods are inherited from AbstractList ) // definition of the Iterator class

COMP103 7:20 Implementing ArrayList Data structure: data count size: returns the value of count get and set: check if within bounds, and access the appropriate value in the array add(index, elem): check if within bounds, (0..size) check if there is room in the array if not, make more room. move other items up, and insert

COMP103 7:21 Implementing ArrayList Data structure: data count remove(index): check if within bounds, (0..size-1) move other items down set data[size-1] to null decrement size iterator new iterator inner class that can step along the array.