COMP 103 Comparators and Comparable. RECAP Iterator and Iterable TODAY Comparator and Comparable ...

19
COMP 103 Comparators and Comparable

Transcript of COMP 103 Comparators and Comparable. RECAP Iterator and Iterable TODAY Comparator and Comparable ...

Page 1: COMP 103 Comparators and Comparable. RECAP  Iterator and Iterable TODAY  Comparator and Comparable  Exceptions 2 RECAP-TODAY.

CO

MP 1

03

Comparators and Comparable

Page 2: COMP 103 Comparators and Comparable. RECAP  Iterator and Iterable TODAY  Comparator and Comparable  Exceptions 2 RECAP-TODAY.

RECAP Iterator and Iterable

TODAY Comparator and Comparable Exceptions

2

RECAP-TODAY

Page 3: COMP 103 Comparators and Comparable. RECAP  Iterator and Iterable TODAY  Comparator and Comparable  Exceptions 2 RECAP-TODAY.

Working with Collections Done:

Declaring and Creating collections Using collections: adding, removing, getting,

setting, putting,…. Iterating through collections

[ Iterators, Iterable, and the "for each" loop ]

What next?

Comparable and Comparator for Sorting Collections - today

Implementing Collection classes – next time

3

Page 4: COMP 103 Comparators and Comparable. RECAP  Iterator and Iterable TODAY  Comparator and Comparable  Exceptions 2 RECAP-TODAY.

Sorting a collection What kinds of collections could you sort?

Set ? Stack ? Queue ? List ? Map ?

How can you sort them? List does not have a sort method. But the Collections class does!

Collections.sort(creatures);Collections.sort(myTaskList);

Collections is a class with lots of useful static methods that apply to collections.

4

Page 5: COMP 103 Comparators and Comparable. RECAP  Iterator and Iterable TODAY  Comparator and Comparable  Exceptions 2 RECAP-TODAY.

Sorting in “Natural order” But what order will it sort into ?

“natural order of the values”

Fine for Strings, Integer, Double Strings ordered alphabetically, as in a phonebook Integer, Double ordered by numerical value

But what’s the “natural order” of Faces in a crowd? Answer:

Whatever you defined it to be, if you defined it. There is no order if you didn’t define it.

How do you define the natural order?

5

Page 6: COMP 103 Comparators and Comparable. RECAP  Iterator and Iterable TODAY  Comparator and Comparable  Exceptions 2 RECAP-TODAY.

“Natural Ordering” & Comparable

If a class implements the Comparable<E> interface Objects from that class have a “natural ordering” Objects can be compared using the compareTo()

method Collections.sort() can sort Lists of those objects

automatically

Comparable <E> is an Interface:Requires an implementation of compareTo(E ob) → int

ob1.compareTo(ob2) returns –ve if ob2 ordered after ob1 returns 0 if ob2 ordered with ob1 returns +ve if ob2 ordered before ob1

6

Page 7: COMP 103 Comparators and Comparable. RECAP  Iterator and Iterable TODAY  Comparator and Comparable  Exceptions 2 RECAP-TODAY.

Eg: Making a “Face” class Comparable

public class Face implements Comparable <Face>{ : public int size(){ // just a helper method return (wd * ht); }

/** Natural ordering is by size, small to large. */ public int compareTo(Face other){

}

if (button.equals(“SmallToBig")) { Collections.sort(crowd);

for (Face f : crowd) UI.print(f.toString());

}

return ( this.size() – other.size() );

if ( this.size() < other.size() ) return -1;else if ( this.size() > other.size() ) return 1;else return 0;

7

Elsewhere, in the program, we might see this

Page 8: COMP 103 Comparators and Comparable. RECAP  Iterator and Iterable TODAY  Comparator and Comparable  Exceptions 2 RECAP-TODAY.

Sorting with ComparatorsSuppose we need two different sorting orders

at different times? Collections.sort(…) has two forms:

1. Sort by the “natural order”

Collections.sort(todoList) the values in todoList must be Comparable i.e. the element class supplies a "compareTo()"

method

2. Sort according to a specified order:

Collections.sort(crowd, faceByArea) faceByArea is a Comparator object for comparing

thevalues in crowd.

Comparable interface for objects that can be compared. method: compareTo()

Comparator An object that can compare other objects, using compare()

8

Page 9: COMP 103 Comparators and Comparable. RECAP  Iterator and Iterable TODAY  Comparator and Comparable  Exceptions 2 RECAP-TODAY.

Sorting with Comparators Collections.sort(crowd, faceByArea);

List

Data

Comparator

-1 / 0 / +1

val1 val2

-ve ⇒ val1 less than val2

0 ⇒ val1 equals val2

+ve ⇒ val1 greater than val2

Sort

9

Page 10: COMP 103 Comparators and Comparable. RECAP  Iterator and Iterable TODAY  Comparator and Comparable  Exceptions 2 RECAP-TODAY.

Comparators Comparator <E> is an Interface Requires

public int compare(E ob1, E ob2);→ –ve if ob1 ordered before ob2→ 0 if ob1 equals ob2→ +ve if ob1 ordered after ob2

/** Compares faces by the position of their top edge */

private class TopToBotComparator implements Comparator<Face>{     public int compare(Face f1, Face f2){       return (f1.getTop() - f2.getTop());     } }

A tiny class! It's really just a method that we can pass around... In java we can only pass around objects, not methods.

10

Page 11: COMP 103 Comparators and Comparable. RECAP  Iterator and Iterable TODAY  Comparator and Comparable  Exceptions 2 RECAP-TODAY.

Using Multiple Comparatorsif (button.equals("SmallToBig")){      Collections.sort(crowd); // use the "natural ordering" on Faces.      render();}else if (button.equals("BigToSmall")){      Collections.sort(crowd, new BigToSmallComparator());       render();} else if (button.equals("LeftToRight")){      Collections.sort(crowd, new LfToRtComparator());      render();} else if (button.equals("TopToBottom")){      Collections.sort(crowd, new TopToBotComparator());      render();}

11

EXAMPLE

Page 12: COMP 103 Comparators and Comparable. RECAP  Iterator and Iterable TODAY  Comparator and Comparable  Exceptions 2 RECAP-TODAY.

Exceptions This will be covered in detail in 2nd year

(SWEN221)

What should a method do when something goes wrong?

Throw an exception! (which is actually an object)

Error of some kind, eg: file doesn’t exist, dividing by zero calling a method on the null object

An exceptional situation, eg: text in file doesn’t have the expected format user enters an unexpected answer

How do you deal with Exceptions? handling (catching) exceptions throwing exceptions

eg. may be thrown by the JVM when executing code.

eg. May be thrown by code from the java library

eg. May be deliberately thrown by your code.

12

Page 13: COMP 103 Comparators and Comparable. RECAP  Iterator and Iterable TODAY  Comparator and Comparable  Exceptions 2 RECAP-TODAY.

Catching exceptionsexceptions 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

UI.println(e3.getMessage());e3.printStackTrace(); }

Informative action for an error condition that the program can’t deal with itself

13

Page 14: COMP 103 Comparators and Comparable. RECAP  Iterator and Iterable TODAY  Comparator and Comparable  Exceptions 2 RECAP-TODAY.

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

14

Page 15: COMP 103 Comparators and Comparable. RECAP  Iterator and Iterable TODAY  Comparator and Comparable  Exceptions 2 RECAP-TODAY.

Throwable objects!

Throwable

ErrorsExceptions

many types (classes)...

subclasses...

(eg: RuntimeException)

15

Page 16: COMP 103 Comparators and Comparable. RECAP  Iterator and Iterable TODAY  Comparator and Comparable  Exceptions 2 RECAP-TODAY.

Types of Exceptions There are lots of kinds of exceptions

RuntimeExceptions don’t have to be handled: An uncaught RuntimeException will result in an error

message You can try-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. Example: IOException

(which is why we always have to use a try…catch when opening files).

An exception object contains information: the state of the execution stack any additional information specific to the exception

16

Page 17: COMP 103 Comparators and Comparable. RECAP  Iterator and Iterable TODAY  Comparator and Comparable  Exceptions 2 RECAP-TODAY.

Throwing exceptions The throw statement causes an exception.

eg from MiniDraw: suppose that 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”);

renderShape();

General RuntimeException object.• Could use a more specific one• Could define our own type of exception

17

Page 18: COMP 103 Comparators and Comparable. RECAP  Iterator and Iterable TODAY  Comparator and Comparable  Exceptions 2 RECAP-TODAY.

Another example from earlier: iterator

private class ArithSequenceIterator implements Iterator <Integer> {private int nextNum;private ArithSequence source;public ArithSequenceIterator(ArithSequence seq) {

source = seq;nextNum = seq.start;

}public boolean hasNext() {

return true; // there is always another one}public Integer next() {

int ans = nextNum;nextNum += source.step;return ans;

}public void remove() { throw new UnsupportedOperationException();}

} Better to put in some informative message!

18

Page 19: COMP 103 Comparators and Comparable. RECAP  Iterator and Iterable TODAY  Comparator and Comparable  Exceptions 2 RECAP-TODAY.

Implementing Collections Part 1: using collections

Different types of collections The Java collections library Interfaces for List, Set, Map, Stack, Queue Using Iterators and Iterable Using 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

19