The Comparable Interface

Slides:



Advertisements
Similar presentations
Computer Science 209 Software Development Equality and Comparisons.
Advertisements

String and Lists Dr. Benito Mendoza. 2 Outline What is a string String operations Traversing strings String slices What is a list Traversing a list List.
©TheMcGraw-Hill Companies, Inc. Permission required for reproduction or display. Chapter 11: Sorting and Searching  Searching Linear Binary  Sorting.
Searching and Sorting I 1 Searching and Sorting 1.
COMP 14 Introduction to Programming Miguel A. Otaduy May 18, 2004.
The UNIVERSITY of NORTH CAROLINA at CHAPEL HILL Adrian Ilie COMP 14 Introduction to Programming Adrian Ilie June 30, 2005.
Comparing Objects in Java. The == operator When you define an object, for instance Person p = new Person("John", 23); we talk about p as if its value.
1 Chapter Two Using Data. 2 Objectives Learn about variable types and how to declare variables Learn how to display variable values Learn about the integral.
Java Primitives The Smallest Building Blocks of the Language (corresponds with Chapter 2)
Programming with Java © 2002 The McGraw-Hill Companies, Inc. All rights reserved. 1 McGraw-Hill/Irwin Chapter 6 Decisions and Conditions.
 The general subject of comparing objects, or object references, can be introduced concretely with strings.  Recall that String is a class, and so strings.
Variables Tutorial 3c variable A variable is any symbol that can be replaced with a number to solve a math problem. An open sentence has at least one.
Chapter 2: Using Data.
Sorting. RHS – SWC 2 Sorting Searching in sorted data is much faster than searching in unsorted data Being able to sort data efficiently is thus a quite.
Course Title: Object Oriented Programming with C++ instructor ADEEL ANJUM Chapter No: 03 Conditional statement 1 BY ADEEL ANJUM (MSc-cs, CCNA,WEB DEVELOPER)
SortingBigOh ASFA AP Computer Science A. Big-O refers to the order of an algorithm runtime growth in relation to the number of items I. O(l) - constant.
Some Standard Classes Goals The Object class The String class Wrapper classes The Math class Random Numbers.
Chapter 10 Defining Classes. The Internal Structure of Classes and Objects Object – collection of data and operations, in which the data can be accessed.
HashCode() 1  if you override equals() you must override hashCode()  otherwise, the hashed containers won't work properly  recall that we did not override.
Sorting. RHS – SOC 2 Sorting Searching in sorted data is much faster (O(log(n)), than searching in unsorted data (O(n)). Being able to sort data efficiently.
Chapter 2 topics Concept # on Java Subset Required for AP Exam print and println10. Testing of output is restricted to System.out.print and System.out.println.
ICT Introduction to Programming Chapter 4 – Control Structures I.
Side effects A side effect is anything that happens in a method other than computing and/or returning a value. Example: public class hello { public int.
Chapter 8 Searching and Sorting © 2006 Pearson Education Inc., Upper Saddle River, NJ. All rights reserved.
The Methods and What You Need to Know for the AP Exam
Sorts, CompareTo Method and Strings
Sorting and "Big Oh" ASFA AP Computer Science A SortingBigOh.
Ordered Structures Wellesley College CS230 Lecture 11
Searching.
Strings, StringBuilder, and Character
IST311 / 602 Cleveland State University – Prof. Victor Matos
EGR 2261 Unit 4 Control Structures I: Selection
Debugging and Random Numbers
Interfaces Professor Evan Korth.
Fundamental of Java Programming Basics of Java Programming
Java Review: Reference Types
Wrapper Classes ints, doubles, and chars are known as primitive types, or built-in types. There are no methods associated with these types of variables.
Primitive Types Vs. Reference Types, Strings, Enumerations
Collections class Method name Description binarySearch(list, value)
String Objects & its Methods
Object Oriented Programming (OOP) LAB # 8
Chapter 7: Strings and Characters
Character Set The character set of C represents alphabet, digit or any symbol used to represent information. Types Character Set Uppercase Alphabets A,
7/8 A Review and new concepts with Integers!
Numbers.
Programming Funamental slides
Variables in Algebra Chapter 1 Section 1.
The compareTo interface
A Different Kind of Variable
Adding Integers Using a Number Line.
CSE 501N Fall ‘09 13: Interfaces and Multiple Representation
COMPUTER 2430 Object Oriented Programming and Data Structures I
Control Structure Chapter 3.
CHAPTER FOUR VARIABLES AND CONSTANTS
OPERATIONS WITH INTEGERS: ADD, SUBTRACT, MULTIPLY & DIVIDE.
Lexical Ordering and Sorting
Data Types and Expressions
Match each word to the correct definition.
The Data Element.
Relational Operators.
Searching.
IST311 / 602 Cleveland State University – Prof. Victor Matos
2009 Test Key.
TCSS 143, Autumn 2004 Lecture Notes
Chapter 13 Abstract Classes and Interfaces Part 01
The Data Element.
Collections class Method name Description binarySearch(list, value)
Multiplying Fractions: Visual Fraction Models
Arrays.
String Methods Strings have actions known as method. We will review a few of the methods associated with strings that are a part of the built in Java.
Presentation transcript:

The Comparable Interface Java The Comparable Interface

Comparable Interface A class implements the Comparable interface when its objects are expected to be arranged into a particular order. For example, the class String implements Comparable, because strings are often compared with each other and arranged into alphabetical order. Numeric classes (such as Integer or Double) implement Comparable since number are often sorted into numeric order. Chapter Topics: The Comparable Interface compareTo() method natural order collating sequence This chapter describes the Java 5.0 version of Comparable, which uses generics. Earlier versions of Java are somewhat different. QUESTION 1: Arrange these strings into order: "orange", "apple", "plum".

Answer: "apple", "orange", "plum". compareTo() could be used to make the same arrangement. Comparable Interface In general, an interface consists of constants and method declarations. A class that implements an interface must implement each of the methods listed in the interface. The Comparable interface consists of just one method: int compareTo( ClassName obj ) // Compare this object with obj. // Return a negative integer, zero, or a positive integer, // when this object is less than, equal, or greater than obj. In the above, " ClassName " stands for the type of the objects. For example, if the objects are Strings, then " ClassName" is String. If some objects are instances of a class that implements Comparable, then each object is less than, equal, or greater than any object of that class. compareTo() returns an integer to show which of these three relations hold. Relation objectA.compareTo( objectB ) objectA Less Than objectB Negative Integer Equals Zero Greater Than Positive Integer

For example, Only the sign of the returned integer matters if the return value is not zero. The magnitude of a returned integer does not signify anything. QUESTION 2: Examine the following declarations. They use the wrapper class Integer. An Integer object holds an integer as its data, plus provides several useful methods (such as compareTo) for working with integers Integer minusTen = new Integer( -10 ); Integer minusFive = new Integer( -5 ); Integer five = new Integer( 5 ); Integer ten = new Integer( 10 ); Integer fifteen = new Integer( 15 ); What is the result of each of the following? five.compareTo( ten ) _______________ ten.compareTo( five ) _______________ five.compareTo( five ) _______________ ten.compareTo( fifteen ) _______________ minusFive.compareTo( ten ) _______________ minusFive.compareTo( minusTen ) _______________ "apple".compareTo("orange") Negative Integer "apple".compareTo("plum") "apple".compareTo("apple") Zero "orange".compareTo("orange") "orange".compareTo("apple") Positive Integer Negative Positive Zero Negative Negative Positive

Natural Order Objects that implement compareTo() can be arranged into a natural order. This order can be visualized as an arrangement of objects from left to right, like on a number line. If an object A is left of another object B in this ordering, then objectA.compareTo(objectB) is negative. For example, X.compareTo("orange") is negative for all the fruit X left of "orange". QUESTION 3: What is "grape".compareTo( "banana" );

Rules for compareTo() Answer: positive With all objects, compareTo() works the way number comparisons work in ordinary arithmetic. Here are a few rules. Most of these are fairly clear if you think about numbers. Say that A, B, and C are Integers. If A.compareTo(B) > 0 then B.compareTo(A) < 0. If A.compareTo(B) > 0 and B.compareTo(C) > 0 then A.compareTo(C) > 0. If A.compareTo(B) == 0 then A.compareTo(Z) and B.compareTo(Z) should give the same result, no matter what Z is. The classes that come with Java follow these rules. If you write a class that implements Comparable, you need to follow these rules. This is not hard to do because most sensible compareTo() methods will do this naturally. QUESTION 4: Say that X.compareTo(Y)==0. Is it then true that X.equals(Y)?

Strings!! All the Rules Here are all the rules for comparing strings, in one annoying list: Rule 1: If A.compareTo(B) == 0, then A and B are the same length (counting all characters, including blanks and punctuation) and each character in A is identical (including case) to the character in B at the same location. Rule 2: Otherwise, if string A is a prefix of string B, then A.compareTo(B) < 0. If B is a prefix of string A, then A.compareTo(B) > 0. Rule 3: Otherwise, find the first differing pair of characters in the strings A and B. Call them Achar and Bchar. Then A.compareTo(B) is negative if Achar comes before Bchar in the alphabet used by Java (and otherwise is positive). The rules about what character comes first in the alphabet depend on what country you are in. This is one of the aspects of internationalization, which is the subject of customizing programs for use in different countries. Lets not worry about that

Sample Implementations public int compareTo( SampleClass other ) { return getWord().compareTo( other.getWord() ); }

Pop Quiz http://chortle.ccsu.edu/java5/Notes/chap53/chap53quiz.html

To Do Complete the Interface Assignment Practice AP Test Elevens Lab On Thursday: Practice Exam: Finish Multiple Choice Start Free Response