Presentation is loading. Please wait.

Presentation is loading. Please wait.

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

Similar presentations


Presentation on theme: "1 Introduction to Searching and Sorting Comparable Interface -Reading p. 717-718 Comparator Interface."— Presentation transcript:

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

2 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 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 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 5 The Comparable Interface Several core Java classes implement Comparable interface. It is also preferable for object1.compareTo(object2) to return 0 if and only if object1.equals(object2) is true.

6 6 The Comparable Interface (cont’d) Example 1: A BankAccount defining the natural ordering as the ascending order of account numbers. import java.util.*; class BankAccount implements Comparable { private int accountNumber; private String name; private double balance;

7 7 The Comparable Interface (cont’d) 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; }

8 8 The Comparable Interface (cont’d) Assuming that account1 and account2 are BankAccount objects, a typical call to the compareTo method is: int comparisonResult = account1.compareTo(account2); if(comparisonResult == 0) System.out.println(“Same account”); else if (comparisonResult < 0) System.out.println(“acountNumber1 is smaller”); else System.out.println(“accountNumber2 is smaller”);

9 9 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.

10 10 The Comparator Interface 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.

11 11 The Comparator Interface public interface Comparator { int compare(Object object1, Object object2); 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

12 12 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.

13 13 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); }

14 14 The Comparator Interface (cont’d) 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)); }

15 15 The Comparator Interface (cont’d) -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]

16 16 Introduction to Generics Beginning with version 5.0, Java allows class and method definitions that include parameters for types Such definitions are called generics –Generic programming with a type parameter enables code to be written that applies to any class

17 17 The ArrayList Class ArrayList is a class in the standard Java libraries –Unlike arrays, which have a fixed length once they have been created, an ArrayList is an object that can grow and shrink while your program is running In general, an ArrayList serves the same purpose as an array, except that an ArrayList can change length while the program is running

18 18 The ArrayList Class The class ArrayList is implemented using an array as a private instance variable –When this hidden array is full, a new larger hidden array is created and the data is transferred to this new array

19 19 The ArrayList Class Why not always use an ArrayList instead of an array? 1.An ArrayList is less efficient than an array 2.It does not have the convenient square bracket notation 3.The base type of an ArrayList must be a class type (or other reference type): it cannot be a primitive type –This last point is less of a problem now that Java provides automatic boxing and unboxing of primitives

20 20 Using the ArrayList Class In order to make use of the ArrayList class, it must first be imported from the package java.util An ArrayList is created and named in the same way as object of any class, except that you specify the base type as follows: ArrayList aList = new ArrayList ();

21 21 Using the ArrayList Class An initial capacity can be specified when creating an ArrayList as well –The following code creates an ArrayList that stores objects of the base type String with an initial capacity of 20 items ArrayList list = new ArrayList (20); –Specifying an initial capacity does not limit the size to which an ArrayList can eventually grow Note that the base type of an ArrayList is specified as a type parameter

22 22 Using the ArrayList Class The add method is used to set an element for the first time in an ArrayList list.add("something"); –The method name add is overloaded –There is also a two argument version that allows an item to be added at any currently used index position or at the first unused position

23 23 Using the ArrayList Class The size method is used to find out how many indices already have elements in the ArrayList int howMany = list.size(); The set method is used to replace any existing element, and the get method is used to access the value of any existing element list.set(index, "something else"); String thing = list.get(index);

24 24 The "For Each" Loop The ArrayList class is an example of a collection class Starting with version 5.0, Java has added a new kind of for loop called a for-each or enhanced for loop –This kind of loop has been designed to cycle through all the elements in a collection (like an ArrayList )

25 25 A for-each Loop Used with an ArrayList (Part 1 of 3)

26 26 A for-each Loop Used with an ArrayList (Part 2 of 3)

27 27 A for-each Loop Used with an ArrayList (Part 3 of 3)

28 28 Collections A Java collection is any class that holds objects and implements the Collection interface –For example, the ArrayList class is a Java collection class, and implements all the methods in the Collection interface –Collections are used along with iterators The Collection interface is the highest level of Java's framework for collection classes –All of the collection classes discussed here can be found in package java.util

29 29 The Collection Landscape

30 30 Wildcards Classes and interfaces in the collection framework can have parameter type specifications that do not fully specify the type plugged in for the type parameter –Because they specify a wide range of argument types, they are known as wildcards public void method(String arg1, ArrayList arg2) –In the above example, the first argument is of type String, while the second argument can be an ArrayList with any base type

31 31 Wildcards A bound can be placed on a wildcard specifying that the type used must be an ancestor type or descendent type of some class or interface –The notation specifies that the argument plugged in be an object of any descendent class of String –The notation specifies that the argument plugged in be an object of any ancestor class of String

32 32 The Collection Framework The Collection interface describes the basic operations that all collection classes should implement –The method headings for these operations are shown on the next several slides Since an interface is a type, any method can be defined with a parameter of type Collection –That parameter can be filled with an argument that is an object of any class in the collection framework

33 33 Method Headings in the Collection Interface ( Part 1 of 10)

34 34 Method Headings in the Collection Interface ( Part 2 of 10)

35 35 Method Headings in the Collection Interface ( Part 3 of 10)

36 36 Method Headings in the Collection Interface ( Part 4 of 10)

37 37 Method Headings in the Collection Interface ( Part 5 of 10)

38 38 Method Headings in the Collection Interface ( Part 6 of 10)

39 39 Method Headings in the Collection Interface ( Part 7 of 10)

40 40 Method Headings in the Collection Interface ( Part 8 of 10)

41 41 Method Headings in the Collection Interface ( Part 9 of 10)

42 42 Method Headings in the Collection Interface ( Part 10 of 10)

43 43 Collection Relationships There are a number of different predefined classes that implement the Collection interface –Programmer defined classes can implement it also A method written to manipulate a parameter of type Collection will work for all of these classes, either singly or intermixed There are two main interfaces that extend the Collection interface: The Set interface and the List interface

44 44 Collection Relationships Classes that implement the Set interface do not allow an element in the class to occur more than once –The Set interface has the same method headings as the Collection interface, but in some cases the semantics (intended meanings) are different –Methods that are optional in the Collection interface are required in the Set interface

45 45 Collection Relationships Classes that implement the List interface have their elements ordered as on a list –Elements are indexed starting with zero –A class that implements the List interface allows elements to occur more than once –The List interface has more method headings than the Collection interface –Some of the methods inherited from the Collection interface have different semantics in the List interface –The ArrayList class implements the List interface

46 46 Methods in the Set Interface (Part 1 of 10)

47 47 Methods in the Set Interface (Part 2 of 10)

48 48 Methods in the Set Interface (Part 3 of 10)

49 49 Methods in the Set Interface (Part 4 of 10)

50 50 Methods in the Set Interface (Part 5 of 10)

51 51 Methods in the Set Interface (Part 6 of 10)

52 52 Methods in the Set Interface (Part 7 of 10)

53 53 Methods in the Set Interface (Part 8 of 10)

54 54 Methods in the Set Interface (Part 9 of 10)

55 55 Methods in the Set Interface (Part 10 of 10)

56 56 Iterators An iterator is an object that is used with a collection to provide sequential access to the collection elements –This access allows examination and possible modification of the elements An iterator imposes an ordering on the elements of a collection even if the collection itself does not impose any order on the elements it contains –If the collection does impose an ordering on its elements, then the iterator will use the same ordering

57 57 The Iterator Interface Java provides an Iterator interface –Any object of any class that satisfies the Iterator interface is an Iterator An Iterator does not stand on its own –It must be associated with some collection object using the method iterator –If c is an instance of a collection class (e.g., HashSet ), the following obtains an iterator for c : Iterator iteratorForC = c.iterator();

58 58 Methods in the Iterator Interface (Part 1 of 2)

59 59 Methods in the Iterator Interface (Part 2 of 2)

60 60 Using an Iterator with a HashSet Object A HashSet object imposes no order on the elements it contains However, an iterator will impose an order on the elements in the hash set –That is, the order in which they are produced by next() –Although the order of the elements so produced may be duplicated for each program run, there is no requirement that this must be the case

61 61 An Iterator (Part 1 of 3)

62 62 An Iterator (Part 2 of 3)

63 63 An Iterator (Part 3 of 3)

64 64 Tip: For-Each Loops as Iterators Although it is not an iterator, a for-each loop can serve the same purpose as an iterator –A for-each loop can be used to cycle through each element in a collection For-each loops can be used with any of the collections discussed here

65 65 For-Each Loops as Iterators (Part 1 of 2)

66 66 For-Each Loops as Iterators (Part 2 of 2)

67 67 The ListIterator Interface The ListIterator interface extends the Iterator interface, and is designed to work with collections that satisfy the List interface –A ListIterator has all the methods that an Iterator has, plus additional methods –A ListIterator can move in either direction along a list of elements –A ListIterator has methods, such as set and add, that can be used to modify elements

68 68 Methods in the ListIterator Interface (Part 1 of 4)

69 69 Methods in the ListIterator Interface (Part 2 of 4)

70 70 Methods in the ListIterator Interface (Part 3 of 4)

71 71 Methods in the ListIterator Interface (Part 4 of 4)

72 72 The ListIterator Cursor Every ListIterator has a position marker known as the cursor –If the list has n elements, they are numbered by indices 0 through n-1, but there are n+1 cursor positions –When next() is invoked, the element immediately following the cursor position is returned and the cursor is moved forward one cursor position –When previous() is invoked, the element immediately before the cursor position is returned and the cursor is moved back one cursor position

73 73 ListIterator Cursor Positions

74 74 Pitfall: next and previous Can Return a Reference Theoretically, when an iterator operation returns an element of the collection, it might return a copy or clone of the element, or it might return a reference to the element Iterators for the standard predefined collection classes, such as ArrayList and HashSet, actually return references –Therefore, modifying the returned value will modify the element in the collection

75 75 An Iterator Returns a Reference (Part 1 of 4)

76 76 An Iterator Returns a Reference (Part 2 of 4)

77 77 An Iterator Returns a Reference (Part 3 of 4)

78 78 An Iterator Returns a Reference (Part 4 of 4)

79 79 Tip: Defining Your Own Iterator Classes There is usually little need for a programmer defined Iterator or ListIterator class The easiest and most common way to define a collection class is to make it a derived class of one of the library collection classes –By doing this, the iterator() and listIterator() methods automatically become available to the program If a collection class must be defined in some other way, then an iterator class should be defined as an inner class of the collection class

80 80 Simple Uses of Inner Classes Inner (or nested) classes are classes defined within other classes –The class that includes the inner class is called the outer class There are four categories of inner classes in Java: 1.Inner classes (non-static) 2.Static inner classes 3.Local classes (defined inside a block of Java code) 4.Anonymous classes (defined inside a block of Java code)

81 81 Simple Uses of Inner Classes An inner class definition is a member of the outer class in the same way that the instance variables and methods of the outer class are members –An inner class is local to the outer class definition –The name of an inner class may be reused for something else outside the outer class definition –If the inner class is private, then the inner class cannot be accessed by name outside the definition of the outer class

82 82 Simple Uses of Inner Classes There are two main advantages to inner classes –They can make the outer class more self- contained since they are defined inside a class –Both of their methods have access to each other's private methods and instance variables Using an inner class as a helping class is one of the most useful applications of inner classes –If used as a helping class, an inner class should be marked private

83 83 Tip: Inner and Outer Classes Have Access to Each Other's Private Members Within the definition of a method of an inner class: –It is legal to reference a private instance variable of the outer class –It is legal to invoke a private method of the outer class Within the definition of a method of the outer class –It is legal to reference a private instance variable of the inner class on an object of the inner class –It is legal to invoke a (nonstatic) method of the inner class as long as an object of the inner class is used as a calling object Within the definition of the inner or outer classes, the modifiers public and private are equivalent

84 84 Class with an Inner Class

85 85 Class with an Inner Class

86 86 Class with an Inner Class

87 87 The.class File for an Inner Class Compiling any class in Java produces a.class file named ClassName.class Compiling a class with one (or more) inner classes causes both (or more) classes to be compiled, and produces two (or more).class files –Such as ClassName.class and ClassName$InnerClassName.class

88 88 Local Classes A local class is defined within a block of Java code. Local classes are completely hidden in their containing block. When a class name is used only within a block it can be defined locally. A local class can access instance variables of the outer class and only the final local variables of the enclosing block.

89 89 Local Classes: Example class LocalClassExample{ private String name = "KFUPM"; public void method ( ) { int j = 20; final int k = 30; class Local { public void test ( ) { //System.out.println(j); //Error as j is not final System.out.println(k); //OK k is final //Like an inner class, instance variables of //the enclosing object can be accessed. System.out.println ( name ) ; } Local loc = new Local ( ) ; loc.test ( ) ; } public static void main ( String [ ] args ) { LocalClassExample obj = new LocalClassExample ( ); obj.method ( ) ; }

90 90 Anonymous Classes It is a local class without a name If only one object has to be created from a class, and there is no need to name the class, then an anonymous class definition can be used –The class definition is embedded inside the expression with the new operator Anonymous class has no constructors It is either derived from a class, or implements an interface. Like: –AnInterface i = new AnInterface ( ) { // methods defs. … } –ASuperclass c = new ASuperclass(…) { // methods defs. … }

91 91 Anonymous Classes

92 92 Anonymous Classes

93 93 Anonymous Classes


Download ppt "1 Introduction to Searching and Sorting Comparable Interface -Reading p. 717-718 Comparator Interface."

Similar presentations


Ads by Google