1 Introduction to Searching and Sorting Comparable Interface -Reading p. 638-640 Comparator Interface.

Slides:



Advertisements
Similar presentations
Java Programming Abstract classes and Interfaces.
Advertisements

Exercise 1 Suppose C is a class that implements interfaces I and J. Which of the following Requires a type cast? C c = ……? I i = …..? J j = …..? c =
Problem Solving 5 Using Java API for Searching and Sorting Applications ICS-201 Introduction to Computing II Semester 071.
INTERFACES IN JAVA 1.Java Does not support Multiple Inheritance directly. Multiple inheritance can be achieved in java by the use of interfaces. 2.We need.
IKI 10100: Data Structures & Algorithms Ruli Manurung (acknowledgments to Denny & Ade Azurat) 1 Fasilkom UI Ruli Manurung (Fasilkom UI)IKI10100: Lecture22.
1 Lecture 23 Searching Overview  What is Searching?  Linear Search and its Implementation.  Brief Analysis of Linear Search.  Binary Search and its.
1 Role of Interfaces in Large-Scale Software l API:Application Programmer’s Interface: The methods that allow a programmer to manipulate the data elements.
Searching. 2 Searching an array of integers If an array is not sorted, there is no better algorithm than linear search for finding an element in it static.
Searching and Sorting I 1 Searching and Sorting 1.
Comparable and Comparator Nuts and Bolts. 2 Nuts and bolts Four methods underlie many of Java’s important Collection types: equals, compare and compareTo,
Unit 261 Introduction to Searching and Sorting Comparable Interface Comparator Interface Algorithm Complexity Classes Exercises.
Comparable and Comparator. Outline of the Student class import java.util.*; public class Student implements Comparable { public Student(String name, int.
1 Lecture 08(API)Lecture 11 Java API and Interfaces l API:Application Programmer’s Interface: The methods that allow a programmer to manipulate the data.
1 More on Inheritance Overview l Object: The father of all classes l Casting and Classes l Object Cloning l Importance of Cloning.
ICS201 Lecture 20 : Searching King Fahd University of Petroleum & Minerals College of Computer Science & Engineering Information & Computer Science Department.
Chapter 13 Interfaces and Inner Classes Slides prepared by Rose Williams, Binghamton University Copyright © 2008 Pearson Addison-Wesley. All rights reserved.
Unit 301 Java Collections Framework: Classes I JCF Class Hierarchy The ArrayList Class The Collections Class.
Java Collections. Lecture Objectives To understand the concepts of Java collections To be able to implement Java programs based on Collections.
Slides prepared by Rose Williams, Binghamton University ICS201 Lecture 24 : Collections King Fahd University of Petroleum & Minerals College of Computer.
1 Exception Handling  Introduction to Exceptions  How exceptions are generated  A partial hierarchy of Java exceptions  Checked and Unchecked Exceptions.
Searching. 2 Searching an array of integers If an array is not sorted, there is no better algorithm than linear search for finding an element in it static.
1 Search & Sorting Using Java API Searching and Sorting Using Standard Classes  Searching data other than primitive type.  Comparable interface.  Implementing.
Unit 261 Introduction to Searching and Sorting Comparable Interface Comparator Interface Algorithm Complexity Classes Exercises.
Slides prepared by Rose Williams, Binghamton University Chapter 16 Collections and Iterators.
Searching. Searching an array of integers If an array is not sorted, there is no better algorithm than linear search for finding an element in it static.
Introduction to Searching and Sorting
Inheritance Part II. Lecture Objectives To learn about inheritance To understand how to inherit and override superclass methods To be able to invoke superclass.
Comparable and Comparator. 2 Comparing our own objects The Object class provides public boolean equals(Object obj) and public int hashCode() methods –For.
CS102--Object Oriented Programming Lecture 15: Interfaces Copyright © 2008 Xiaoyan Li.
1 Introduction to Searching and Sorting Comparable Interface -Reading p Comparator Interface.
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.
Searching Also: Logarithms. 2 Searching an array of integers If an array is not sorted, there is no better algorithm than linear search for finding an.
Set, TreeSet, TreeMap, Comparable, Comparator. Def: The abstract data type set is a structure that holds objects and satifies ARC: Objects can be added.
CMSC 202 Interfaces. 11/20102 Classes and Methods When a class defines its methods as public, it describes how the class user interacts with the method.
I NTERFACES Prepared by Miss Simab Shahid Lecturer computer Science and Software Engineering department, University of Hail Chapter.
Collections F The limitations of arrays F Java Collection Framework hierarchy  Use the Iterator interface to traverse a collection  Set interface, HashSet,
© 2000 McGraw-Hill Introduction to Object-Oriented Programming with Java--WuChapter Chapter 10 Sorting and Searching.
Searching Also: Logarithms. 2 Searching an array of integers If an array is not sorted, there is no better algorithm than linear search for finding an.
Java the UML Way versjon Only to be used in connection with the book "Java the UML Way", by Else Lervik and.
Chapter 9 Searching and Sorting
Copyright © 2014 by John Wiley & Sons. All rights reserved.1 Chapter 10 - Interfaces.
Chapter 3 Inheritance and Polymorphism Goals: 1.Superclasses and subclasses 2.Inheritance Hierarchy 3.Polymorphism 4.Type Compatibility 5.Abstract Classes.
Comparison-Based Sorting & Analysis Smt Genap
Some Standard Classes Goals The Object class The String class Wrapper classes The Math class Random Numbers.
©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. 4 th Ed Chapter Chapter 11 Searching and Sorting.
Comparable and Comparator Nuts and Bolts. Sets A set is a collection in which all elements are unique—an element is either in the set, or it isn’t In.
Review TEST 2 Chapters 4,5,7. QUESTION For which type of operands does the == operator always work correctly: (a) int, (b) double, or (c) String?
Interfaces and Inner Classes
Searching and Sorting 14ACEHRPT Copyright © 2011 by Maria Litvin, Gary Litvin, and Skylight Publishing. All rights reserved. Java Methods Object-Oriented.
The Java Tutorials Comparable and Comparator. Object Ordering A List may be sorted as follows. Collections.sort(l); If the List consists of String elements,
CIS3023: Programming Fundamentals for CIS Majors II Summer 2010 Ganesh Viswanathan Interfaces (Part II) Course Lecture Slides 28 June 2010 “A picture is.
Chapter 13 Interfaces and Inner Classes Slides prepared by Rose Williams, Binghamton University Copyright © 2008 Pearson Addison-Wesley. All rights reserved.
1 CSE 331 Comparing objects; Comparable, compareTo, and Comparator slides created by Marty Stepp based on materials by M. Ernst, S. Reges, D. Notkin, R.
More constructors 1. Constructors  recall that a public constructor is what a client uses to create an object  the purpose of a constructor is to initialize.
The Methods and What You Need to Know for the AP Exam
CIS3023: Programming Fundamentals for CIS Majors II
SELECTION STATEMENTS (1)
Introduction to Searching and Sorting
Comparable and Comparator Interfaces
Comparable and Comparator
CMSC 202 Interfaces.
Comparable and Comparator
Interfaces and Inner Classes
مظفر بگ محمدی دانشگاه ایلام
Comparable and Comparator Interfaces
CMSC 202 Interfaces.
Lexical Ordering and Sorting
CMSC 202 Interfaces.
Comparable and Comparator Interfaces
Presentation transcript:

1 Introduction to Searching and Sorting Comparable Interface -Reading p Comparator Interface

2 The Comparable Interface The Comparable interface is in the java.lang package, and so is automatically available to any program It has only the following method heading that must be implemented: public int compareTo(Object other); It is the programmer's responsibility to follow the semantics of the Comparable interface when implementing it

3 The Comparable Interface Semantics The method compareTo must return –A negative number if the calling object "comes before" the parameter other –A zero if the calling object "equals" the parameter other –A positive number if the calling object "comes after" the parameter other If the parameter other is not of the same type as the class being defined, then a ClassCastException should be thrown

4 The Comparable Interface Semantics Almost any reasonable notion of "comes before" is acceptable –In particular, all of the standard less-than relations on numbers and lexicographic ordering on strings are suitable The relationship "comes after" is just the reverse of "comes before"

5 The Comparable Interface The Comparable interface of java.lang public interface Comparable{ public abstract int compareTo(Object object); } If a class implements Comparable interface, the compareTo method defines the natural ordering of its objects when sorted. By repeated calls to compareTo method, The sorting algorithms will be able to sort, according to the natural ordering, a list of objects belonging to a class implementing Comparable interface. Several core Java classes implement Comparable interface. A user defined class that implements Comparable should implement the compareTo method such that : object1.compareTo(object2) is: 0if object1 “is equal to” object2 > 0if object1 “is greater than” object2 < 0if object1 “is less than” object2

6 The Comparable Interface (cont’d) It is also preferable for object1.compareTo(object2) to return 0 if and only if object1.equals(object2) is true. Example 1: A BankAccount defining the natural ordering as the ascending order of accountNumbers. import java.util.*; class BankAccount implements Comparable{ private int accountNumber; private String name; private double balance; public int compareTo(Object object){ BankAccount account = (BankAccount) object; if(accountNumber < account.accountNumber) return -1; else if(accountNumber == account.accountNumber) return 0; else return 1; }

7 The Comparable Interface (cont’d) public String toString(){ return "Account#: " + accountNumber + ", Name: " + name + ", Balance: " + balance + " SR"; }} Assuming that account1 and account2 are BankAccount objects, a typical call to the compareTo method is: 1. int comparisonResult = account1.compareTo(account2); 2. if(comparisonResult == 0) 3. System.out.println(“Same account”); 4. else if (comparisonResult < 0) 5. System.out.println(“acountNumber1 is smaller”); 6. else 7. System.out.println(“accountNumber2 is smaller”);

8 The Comparator Interface If we want to sort objects of a class which does not implement Comparable interface, or the class implements Comparable but we want To order its objects in a way different from the natural ordering defined by Comparable, the java.util.Comparator interface should be used. The Comparator interface is one of the java collections framework interfaces. The Java collection framework is a set of important utility classes and interfaces in the java.util package for working with collections. A collection is a group of objects. Comparator interface defines how collection objects are compared. public interface Comparator{ public abstract int compare(Object object1, Object object2); public abstract boolean equals(Object object); } A class that implements Comparator should implement the compare method such that its returned value is: 0if object1 “is equal to” object2 > 0if object1 “is greater than” object2 < 0if object1 “is less than” object2

9 The Comparator Interface (cont’d) It is also preferable for the compare method to return 0 if and only if object1.equals(object2) is true. The compare method throws a ClassCastException if the type of object1 and that of object2 are not compatible for comparison. The equals method concerns the Comparator object. It returns true if its parameter is a Comparator object and if it uses the same ordering as the invoking (calling) Comparator object; otherwise it returns false. Note: Since each class inherits the equals method from the Object class, it is not necessary for a class that implements the Comparator interface to implement the equals method to be a concrete class. In our examples concerning the Comparator interface, the equals method will not be implemented.

10 The Comparator Interface (cont’d) Example 2: This example sorts the strings in reverse order of the alphabetical one. import java.util.*; class StringReverseComparator implements Comparator{ public int compare(Object object1, Object object2){ String string1 = object1.toString(); String string2 = object2.toString(); // Reverse the comparison return string2.compareTo(string1); } } class Test { public static void main(String[] args) { string[] array={"Ahmad","Mohammad","Ali","Hisham","Omar","Bilal","Hassan"}; Arrays.sort(array,new StringReverseComparator()); System.out.println(Arrays.asList(array)); }} -The sort method,in the Arrays class, sorts the array “array” according to the comparator object. Notice the comparator object is provided as a parameter for the sorting method; it is an object from the class StringReverseComparator. -After printing, we get the following order: [Omar, Mohammad, Hisham, Hassan, Bilal, Ali, Ahmad]

11 The Comparator Interface (cont’d) Example 3: Here the order of the comparator is the descending order of the absolute values import java.util.*; class MyComparator implements Comparator { public int compare(Object obj1, Object obj2) { int i1 = ((Integer)obj1).intValue(); int i2 = ((Integer)obj2).intValue(); return Math.abs(i2) - Math.abs(i1); }} class TestCollections2 { public static void main(String args[]) { Integer[] array = {new Integer(-200),new Integer(100), new Integer(400),new Integer(-300)}; Arrays.sort(array); System.out.println("Natural ordering: " + Arrays.asList(array)); Arrays.sort(array, new MyComparator()); // sorting acording to MyComparator System.out.println("My own ordering : " + Arrays.asList(array)); }

12 The Comparator Interface (cont’d) Example 4: Here we want to order the BankAccount objects, not according to their natural ordering as defined before, but according to the opposite of the alphabetical order of the names of their owners. 2 class MyComparator implements Comparator{ 3 public int compare(Object object1, Object object2){ 4 BankAccount account1 = (BankAccount) object1; 5BankAccount account2 = (BankAccount)object2; 6String string1 = account1.getName(); 7String string2 = account2.getName(); 8// Reverse the comparison 9 return string2.compareTo(string1); 10 } 11 }

13 -Example 5: Consider the following Student class class Student { private String name; private int id; public Student( String newName, int id ) { name = newName; this.id = id;} public String getName(){ return name; } public int getId(){ return id;} public String toString() { return name + ":" + id; } } Consider the following class the implements Comparator class StudentNameComparator implements Comparator { public int compare( Object leftOb, Object rightOb ) { String leftName = ((Student) leftOb).getName(); String rightName = ((Student) rightOb).getName(); return leftName.compareTo( rightName );}} In order to sort students alphabetically by their names, we need to call a Arrays.sort method with 2 parameters; an array of students and an object from StudentNameComparator class

14 Example 5 (continued) Consider now the following class class StudentIdComparator implements Comparator { public int compare( Object b1, Object b2 ) { long leftId = ((Student) b1).getId(); long rightId = ((Student) b2).getId(); if ( leftId < rightId ) return -1; else if ( leftId > rightId ) return 1; else return 0; // the above if construct can be replaced by a single statement // return leftId-rightId; }} In order to sort students by ascending orderof their id numbers, we need to call a Arrays.sort method with 2 parameters; an array of students and an object from StudentNameComparator class

15 Example 5 (continued) The following is a test class to see how sorting works for an array of student objects. It is done either alphabetically, or by id. import java.util.*; class Test { public static void main(String args[]) { Student[] sts = { new Student( "Ahmad", 520 ), new Student( "Rashed", 210 ),new Student( "Bandar", 101 ),new Student("Hatem",992) }; //Sort the array alphabetically Arrays.sort( sts, new StudentNameComparator() ); System.out.println("Students sorted alphabetically"); for ( int k = 0; k < sts.length; k++ ) System.out.println( sts[k]); //Sort the array by ascending id numbers Arrays.sort( sts, new StudentIdComparator() ); System.out.println("Students sorted by id numbers"); for ( int k = 0; k < sts.length; k++ ) System.out.println( sts[k]);}}