Implementing Comparable

54
Implementing Comparable public class Rational implements Comparable { public int compareTo (Object obj) { final double TOLERANCE = .0001; Rational other = (Rational) obj; double otherRational = (double) other.numerator/ other.denominator; double thisRational = (double) this.numerator / this.denominator; double difference = thisRational - otherRational; int result = 0; if (Math.abs(difference) < TOLERANCE) result = 0; else if (difference > 0) result = 1; else result = -1; return result; } }

description

Implementing Comparable. public class Rational implements Comparable { public int compareTo (Object obj) { final double TOLERANCE = .0001; Rational other = (Rational ) obj; double otherRational = (double) other. numerator/ other. denominator; - PowerPoint PPT Presentation

Transcript of Implementing Comparable

Page 1: Implementing Comparable

Implementing Comparablepublic class Rational implements Comparable { public int compareTo (Object obj) { final double TOLERANCE = .0001; Rational other = (Rational) obj; double otherRational = (double) other.numerator/ other.denominator; double thisRational = (double) this.numerator / this.denominator; double difference = thisRational - otherRational; int result = 0; if (Math.abs(difference) < TOLERANCE)

result = 0; else if (difference > 0) result = 1; else

result = -1; return result; }}

Page 2: Implementing Comparable

ArrayAn ordered list of values of the same type.

That type can be primitive or reference (class or interface).

Arrays are objects (reference types).

Arrays are of fixed size and are always bound checked.

The length of array: ia.length

Index starts from 0. An array of size N is indexed from 0 to N-1

Page 3: Implementing Comparable

Array Examplesint[] ia = new int[3]; ia[0] = 1; ia[1] = 2; ia[2] = 3; //-----------------------int ia[] = new int[3]; //-----------------------int[] ia = { 1, 2, 3};

float[][] mat = new float[4][5]; for (int y = 0; y < mat.length; y++) {   for (int x = 0; x < mat[y].length; x++)     mat[y][x] = 0.0; } // mat.length = number of rows// mat[y].length = number of columns in row y

Page 4: Implementing Comparable

Variable length array int [][] table; table = new int[4][]; table [0] = new int [10]; table [1] = new int [20]; table [2] = new int [30]; table [3] = new int [40]; int max = 0; for (int i = 0; i < table.length; i++) for (int j = 0; j < table[i].length; j++) if (table[i][j] > max)

max = table [i][j];

Page 5: Implementing Comparable

4 Dimensional array

int [][][][] table = new int[5][6][7][8];. . .

int a,b,c,d,max = 0; for (a = 0; a < table.length; a++) for (b = 0; b < table[a].length; b++)

for (c = 0; c < table[a][b].length; c++) for (d = 0; d < table [a][b][c].length; d++)

if (table[a][b][c][d] > max) max = table [a][b][c][d];

Page 6: Implementing Comparable

Arrays as Parameters

An array reference can be passed as a parameter during a method call

All reference parameters create aliases

Changing an array element in the method changes the original

Page 7: Implementing Comparable

Arrays of Objects The elements of an array can be object references

The following declaration reserves space to store 25 references to String objects  String[] words = new String[25];

The declaration does NOT create the String objects themselves

Each object stored in an array must be instantiated separately

Page 8: Implementing Comparable

Example: GradeRange.javapublic class GradeRange { public static void main (String[] args) { String[] grades = {"A", "A-", "B+", "B", "B-", "C+", "C", "C-", "D+", "D", "D-", "F"}; int[] cutoff = {95, 90, 87, 83, 80, 77, 73, 70, 67, 63, 60, 0}; for (int level = 0; level < cutoff.length; level++) System.out.println (grades[level] + "\t" + cutoff[level]); }}

Page 9: Implementing Comparable

Example: Wordsclass Words { public static void main (String[] args) { String title; int nbrPages; Dictionary webster = new Dictionary ("Webster's"); Book myBook = new Book ("Java Solutions", 526); Book [] bookCollection = new Book[5]; bookCollection[0] = webster; bookCollection[1] = myBook; bookCollection[2] = new Dictionary ("Noah's", 948); bookCollection[3] = new Book("Art of Programming", 500); bookCollection[4] = new Book("Science of Programming", 700);

Page 10: Implementing Comparable

Words: Continued for (int i = 0; i < bookCollection.length; i++) { title = bookCollection[i].getTitle(); nbrPages = bookCollection[i].pageMessage(); System.out.print((i + 1) + ") " + title + " with " + nbrPages + " pages."); if (bookCollection[i] instanceof Dictionary) ((Dictionary) bookCollection[i]).definitionMessage(); else System.out.println(""); } }}

Page 11: Implementing Comparable

Command Line Argumentspublic class CommandLineArguments {

public static void main(String[] args) { int length = args.length; System.out.println("args.length=" + length); for (int i = 0; i < length; i++) { System.out.println("args[" + i + "]=" + args[i]); } }}

Page 12: Implementing Comparable

Command Line ArgumentsOutput:C:\Examples>java CommandLineArguments args.length=0

C:\Examples>java CommandLineArguments Hello World! args.length=2 args[0]=Hello args[1]=World!

Page 13: Implementing Comparable

Selection Sortpublic class Sorts { public static void selectionSort(int[] numbers) { int min, temp; for (int index = 0; index < numbers.length-1; index++) { min = index; for (int scan = index+1; scan < numbers.length; scan++) if (numbers[scan] < numbers[min]) min = scan; // Swap the values temp = numbers[min]; numbers[min] = numbers[index]; numbers[index] = temp; } }

Page 14: Implementing Comparable

Example: SortGrades.javapublic class SortGrades { public static void main (String[] args) { int[] grades = {89, 94, 69, 80, 97, 85, 73, 91, 77, 85, 93}; Sorts.selectionSort(grades); for (int index = 0; index < grades.length; index++) System.out.print (grades[index] + " "); }}

Page 15: Implementing Comparable

Sorting Arrays of Objectspublic class Sorts { public static void insertionSort(Comparable[] objects) { for (int index = 1; index < objects.length; index++) { Comparable key = objects[index]; int position = index; // shift larger values to the right while (position > 0 && objects[position-1].compareTo(key) > 0) { objects[position] = objects[position-1]; position--; } objects[position] = key; } }

Page 16: Implementing Comparable

Example: Contact.javaclass Contact implements Comparable { private String firstName, lastName, phone; public Contact(String firstName, String lastName, String phone) { this.firstName = firstName; this.lastName = lastName; this.phone = phone; } public String toString () { return lastName + ", " + firstName + "\t" + phone; }

Page 17: Implementing Comparable

Example: Contact.java public int compareTo (Object other) { int result; if (lastName.equals(((Contact)other).lastName)) { result = firstName.compareTo(((Contact)other).firstName); } else { result = lastName.compareTo(((Contact)other).lastName); } return result; }}

Page 18: Implementing Comparable

Example: SortPhoneList.javapublic class SortPhoneList { public static void main (String[] args) { Contact[] friends = new Contact[7]; friends[0] = new Contact("John", "Smith", "610-555-7384"); friends[1] = new Contact(…); friends[2] = new Contact(…); friends[3] = new Contact(…); friends[4] = new Contact(…); friends[5] = new Contact(…); friends[6] = new Contact("Marsha", "Grant", "243-555-2837"); Sorts.insertionSort(friends); for (int index = 0; index < friends.length; index++) System.out.println (friends[index]); }}

Page 19: Implementing Comparable

Vector ClassA variable-sized list of objects.Methods:

void addElement(Object obj) void insertElementAt(Object obj, int i) void setElementAt(Object obj, int i) Object remove(int i) boolean removeElement(Object obj) void removeElementAt(int i) void clear() boolean contains(Object obj) int indexOf(Object obj) Object elementAt(int i) boolean isEmpty() int size()

Page 20: Implementing Comparable

Example: Beatles.javaimport java.util.Vector;public class Beatles { public static void main (String[] args) { Vector band = new Vector(); band.addElement ("Paul"); band.addElement ("Pete"); band.addElement ("John"); band.addElement ("George"); System.out.println (band); band.removeElement ("Pete"); System.out.println (band); System.out.println ("At index 1: "+ band.elementAt(1)); band.insertElementAt ("Ringo", 2); System.out.println (band); System.out.println ("Size of the band: " + band.size()); }}

Page 21: Implementing Comparable

Example: Beatles.javaOutputC:\Examples>java Beatles[Paul, Pete, John, George][Paul, John, George]At index 1: John[Paul, John, Ringo, George]Size of the band: 4

Page 22: Implementing Comparable

Applet Class Hierarchy

Page 23: Implementing Comparable

Applet Methods called by the system

public void init()When the applet is first loaded. Do initialization here. public void start()When the applet is displayed. public void stop()When the browser leaves the page containing the applet. public void destroy()public void paint(Graphics g)

Page 24: Implementing Comparable

GUI – graphical user interface.

Users interact with various elements on the screen

The user expresses intent by clicking a mouse or by typing a letter on the keyboard.

The user action is an event

Page 25: Implementing Comparable

Event an object that represents a user action at the computer’s interface

Events can be classified by

the action that created them causes -- mouse pressed or key pressed, etc.

Events can also can be generated by other programs. (timer)

the source – button, slide-bar, etc.. Different sources of events are represented by different

classes: MouseEvent, ActionEvent, etc.

Page 26: Implementing Comparable

GUI usage requires handling GUI events

GUI components are the “source” of events.

Small event-handling programs should be constructed to handle specific events. Small programs reduce complexity

Programs that handle events from a particular GUI component, should be registered with the source.GUI components maintain a “registration list” of interested listeners

When an event occurs at the GUI component, all programs on the “registration list” are given data about the event

Page 27: Implementing Comparable

Listenersan object that waits for and responses to particular types of events.

There are different types of listeners represented by different listener interfaces: MouseListener, ActionListener, etc.

A listener class implements one of the listener interfaces.

Page 28: Implementing Comparable

Delegation ModelHas

A component that generates eventsAn object that deals with the event.

Important features of this modelAny component can be the source of an eventAny class can be a listener for an event if it implements the appropriate listener interfaceThe event is only sent to listeners that are registered with the source of the event

Page 29: Implementing Comparable

Events and Listeners

Source

This object mayThis object maygenerate an eventgenerate an event

Listener

This object waits for andThis object waits for andresponds to an eventresponds to an event

Event

When an event occurs, the generator callsWhen an event occurs, the generator callsthe appropriate method of the listener,the appropriate method of the listener,

passing an object that describes the eventpassing an object that describes the event

Page 30: Implementing Comparable

To build a listener that responds to an event,

create an object instance of a class that implements the listener interface

register the listener to the graphical component that generates the event (typically an add method of the source)

when an event occurs at the source, the appropriate method of the listener is called automatically

the listener receives an “event object” as a parameter.

information in the event object can be used to determine the program’s reaction to the event

Page 31: Implementing Comparable

Interface MouseListenervoid mousePressed(MouseEvent event)

void mouseReleased(MouseEvent event)

void mouseClicked(MouseEvent event)

void mouseEntered(MouseEvent event)

void mouseExited(MouseEvent event)

Page 32: Implementing Comparable

Class MouseEventPoint getPoint()

int getX()

int getY()

int getClickCont()

Page 33: Implementing Comparable

Listener: DotsMouseListener.java

import java.applet.Applet;import java.awt.*;import java.awt.event.*;class DotsMouseListener implements MouseListener { private Dots applet; public DotsMouseListener(Dots applet) { this.applet = applet; } public void mouseClicked(MouseEvent event) { Point clickPoint = event.getPoint(); applet.setPoint (clickPoint); applet.repaint(); } public void mousePressed(MouseEvent event) {} public void mouseReleased(MouseEvent event) {} public void mouseEntered(MouseEvent event) {} public void mouseExited(MouseEvent event) {}}

Page 34: Implementing Comparable

Example: Dots.java

import java.applet.Applet;import java.awt.*;public class Dots extends Applet { private final int APPLET_WIDTH = 200; private final int APPLET_HEIGHT = 100; private final int RADIUS = 6; private Point clickPoint = null; public void init() { DotsMouseListener listener = new DotsMouseListener(this); addMouseListener(listener); setBackground(Color.black); setSize(APPLET_WIDTH, APPLET_HEIGHT); }

Page 35: Implementing Comparable

Dots.java (continued)

public void paint(Graphics page) { page.setColor (Color.green); if (clickPoint != null) page.fillOval(clickPoint.x - RADIUS, clickPoint.y - RADIUS, RADIUS * 2, RADIUS * 2); } public void setPoint(Point point) { clickPoint = point; }}

Page 36: Implementing Comparable

Interface MouseMotionListener

void mouseMoved(MouseEvent event)

void mouseDragged(MouseEvent event)

Page 37: Implementing Comparable

Example RubberLines.javaimport java.applet.Applet;import java.awt.*;import java.awt.event.*;public class RubberLines extends Applet implements MouseListener, MouseMotionListener { private final int APPLET_WIDTH = 200; private final int APPLET_HEIGHT = 200; private Point point1 = null; private Point point2 = null; public void init() { addMouseListener(this); addMouseMotionListener(this); setBackground(Color.black); setSize(APPLET_WIDTH, APPLET_HEIGHT); }

Page 38: Implementing Comparable

Example RubberLines.java public void paint(Graphics page) { page.setColor (Color.green); if (point1 != null && point2 != null) page.drawLine (point1.x, point1.y, point2.x, point2.y); } public void mousePressed(MouseEvent event) { point1 = event.getPoint(); } public void mouseDragged(MouseEvent event) { point2 = event.getPoint(); repaint(); }

Page 39: Implementing Comparable

Example RubberLines.java public void mouseClicked(MouseEvent event) {} public void mouseReleased(MouseEvent event) {} public void mouseEntered(MouseEvent event) {} public void mouseExited(MouseEvent event) {} public void mouseMoved(MouseEvent event) {}}

Page 40: Implementing Comparable

Handling Key Presses

Interface KeyListener void keyPressed(KeyEvent event) void keyReleased(KeyEvent event) void keyTyped(KeyEvent event)

Class KeyEvent int getKeyCode() constants for all keys

Page 41: Implementing Comparable

Example: Direction.javaimport java.applet.*;import java.awt.*;import java.awt.event.*;public class Direction extends Applet { private final int APPLET_WIDTH = 200; private final int APPLET_HEIGHT = 200; private final int JUMP = 5; // increment for image movement private final int IMAGE_SIZE = 31; private Image up, down, right, left, currentImage; private AudioClip bonk; private int x, y;

Page 42: Implementing Comparable

Example: Direction.javapublic void init() { requestFocus(); // make sure the applet has the keyboard focus addKeyListener(new DirectionKeyListener()); x = y = 0; up = getImage (getCodeBase(), "cyanUp.gif"); down = getImage (getCodeBase(), "cyanDown.gif"); left = getImage (getCodeBase(), "cyanLeft.gif"); right = getImage (getCodeBase(), "cyanRight.gif"); currentImage = right; bonk = getAudioClip (getCodeBase(), "bonk.au"); setBackground (Color.black); setSize (APPLET_WIDTH, APPLET_HEIGHT); } public void paint (Graphics page) { page.drawImage (currentImage, x, y, this); }

Page 43: Implementing Comparable

Example: Direction.java private class DirectionKeyListener implements KeyListener { public void keyPressed (KeyEvent event) { switch (event.getKeyCode()) { case KeyEvent.VK_UP: currentImage = up; if (y > 0) y -= JUMP; break; case KeyEvent.VK_DOWN: currentImage = down; if (y < APPLET_HEIGHT-IMAGE_SIZE) y += JUMP; break; case KeyEvent.VK_LEFT: currentImage = left; if (x > 0) x -= JUMP; break;

Page 44: Implementing Comparable

Example: Direction.java case KeyEvent.VK_RIGHT: currentImage = right; if (x < APPLET_WIDTH-IMAGE_SIZE) x += JUMP; break; default: bonk.play(); } repaint(); } public void keyTyped (KeyEvent event) {} public void keyReleased (KeyEvent event) {} }}

Page 45: Implementing Comparable

Applet Methods If an applet requires additional data, image or sound files stored on the same host as the applet, the following methods can be used to locate the host.

public URL getCodeBase()Returns URL of the directory that contains the applet’s .class file

public URL getDocumentBase()Returns URL of the current HTML document

Page 46: Implementing Comparable

Loading Audios / Images

Page 47: Implementing Comparable

URL

The URL form is:protocol://host_name/path_name/file_name

protocol is the format for transferring files (http, ftp, gopher)

host_name is a hierarchical listing of java domains listed in increasing order of generality

(java.sun.com, cs.some.edu:8080 – port number)

path_name is a hierarchical listing of the file structure listed in decreasing order of generality (products/jdk/1.1/docs/api)

Page 48: Implementing Comparable

Absolute & Relative URLsAbsolute URL

http://java.sun.com/products/jdk/1.1/docs/api/tree.html

Relative URL (operates within context of above URL) packages.html (replaces tree.html)foo/hello.html (replaces tree.html)/bar/notes.html (replaces /api/tree.html)

If the image named test.gif is contained in the relative URL /images then the following code will load the image

URL testURL = new URL(getCodeBase(), “/images/test.gif”);Image testImage = getImage(testURL);

Page 49: Implementing Comparable

URL Class package java.net

URL ConstructorsURL(String name) URL(URL base, String relative)URL(String protocol, String host, String file)URL(String protocol, String host, int port, String file)

URL MethodsString getFile() String getHost()int getPort()String getProtocol()

Page 50: Implementing Comparable

AnimationAn animation is a constantly changing series of pictures or images that create the illusion of movement

We can create animations in Java by changing a picture slightly over time

The speed of a Java animation is usually controlled by a Timer object

Timer class Timer(int delay, ActionListener listener) void addActionListener(ActionListener listener) boolean isRunning() void start() void stop()

Page 51: Implementing Comparable

Example: Rebound.javaimport java.applet.Applet;import java.awt.*;import java.awt.event.*;import javax.swing.Timer;public class Rebound extends Applet { private final int APPLET_WIDTH = 200; private final int APPLET_HEIGHT = 100; private final int IMAGE_SIZE = 35; private final int DELAY = 20; private Timer timer; private Image image; private int x, y, moveX, moveY;

Page 52: Implementing Comparable

Example: Rebound.java public void init() { addMouseListener(new ReboundMouseListener()); timer = new Timer(DELAY, new ReboundActionListener()); timer.start(); x = 0; y = 40; moveX = moveY = 3; image = getImage(getCodeBase(), "happyFace.gif"); setBackground(Color.black); setSize(APPLET_WIDTH, APPLET_HEIGHT); } public void paint(Graphics page) { page.drawImage(image, x, y, this); }

Page 53: Implementing Comparable

Example: Rebound.java private class ReboundMouseListener implements MouseListener { public void mouseClicked(MouseEvent event) { if (timer.isRunning()) timer.stop(); else timer.start(); } public void mouseEntered(MouseEvent event) {} public void mouseExited(MouseEvent event) {} public void mousePressed(MouseEvent event) {} public void mouseReleased(MouseEvent event) {} }

Page 54: Implementing Comparable

Example: Rebound.java private class ReboundActionListener implements ActionListener { public void actionPerformed(ActionEvent event) { x += moveX; y += moveY; if (x <= 0 || x >= APPLET_WIDTH-IMAGE_SIZE) moveX = moveX * -1; if (y <= 0 || y >= APPLET_HEIGHT-IMAGE_SIZE) moveY = moveY * -1; repaint(); } }}