Добавил:
Upload Опубликованный материал нарушает ваши авторские права? Сообщите нам.
Вуз: Предмет: Файл:
Ganesh_JavaSE7_Programming_1z0-804_study_guide.pdf
Скачиваний:
94
Добавлен:
02.02.2015
Размер:
5.88 Mб
Скачать

Chapter 6 Generics and Collections

and removeLast() methods from the Deque interface to realize the methods of the SplQueue class. In your main() method, you instantiate the SplQueue and called the addInQueue() method of the SplQueue class. After it, you remove one customer from the front and one from the end, and print the contents of the queue before and after this removal. Well, it is working as you expected.

Comparable and Comparator Interfaces

As their names suggest, Comparable and Comparator interfaces are used to compare similar objects (for example, while performing searching or sorting). Assume that you have a container containing a list of Person object. Now, how you compare two Person objects? There are any number of comparable attributes, such as SSN, name,

driving-license number, and so on. Two objects can be compared on SSN as well as person’s name; this depends on the context. Hence, the criterion to compare the Person objects cannot be predefined; a developer has to define this criterion. Java defines Comparable and Comparator interfaces to achieve the same.

The Comparable class has only one method compareTo(), which is declared as follows:

int compareTo(Element that)

Since you are implementing the compareTo() method in a class, you have this reference available. You can compare the current element with the passed Element and return an int value. What should the int value be? Well, here are the rules for returning the integer value:

return 1 if current object > passed object return 0 if current object == passed object return -1 if current object < passed object

Now, an important question: what does >, < or == mean for an Element? Hmm, it is left to you to decide how to compare two objects! But the meaning of comparison should be a natural one; in other words, the comparison should mean natural ordering. For example, you saw how Integers are compared with each other, based on a numeric order, which is the natural order for Integer types. Similarly, you compare Strings using lexicographic comparison, which is the natural order for Strings. For user-defined classes, you need to find the natural order in which you can compare the objects. For example, for a Student class, StudentId might be the natural order for comparing Student objects. Listing 6-23 implements a simple Student class now.

Listing 6-23.  ComparatorTest.java

// This program shows the usage of Comparable interface

import java.util.*;

class Student implements Comparable<Student> { String id;

String name; Double cgpa;

public Student(String studentId, String studentName, double studentCGPA) { id = studentId;

name = studentName; cgpa = studentCGPA;

}

public String toString() {

return " \n " + id + " \t " + name + " \t " + cgpa;

}

189

Chapter 6 Generics and Collections

public int compareTo(Student that) { return this.id.compareTo(that.id);

}

}

class ComparatorTest {

public static void main(String []args) {

Student []students = { new Student("cs011", "Lennon ", 3.1), new Student("cs021", "McCartney", 3.4),

new Student("cs012", "Harrison ", 2.7), new Student("cs022", "Starr ", 3.7) };

 

 

 

 

 

 

System.out.println("Before sorting by student ID");

 

System.out.println("Student-ID \t

Name \t

CGPA (for 4.0) ");

 

System.out.println(Arrays.toString(students));

 

 

 

 

 

 

Arrays.sort(students);

 

 

 

 

 

 

 

 

System.out.println("After sorting by student ID");

 

System.out.println("Student-ID \t

Name \t

CGPA (for 4.0) ");

 

System.out.println(Arrays.toString(students));

}

 

 

 

 

 

}

 

 

 

 

 

 

 

 

 

 

It prints the following:

 

 

 

 

 

 

 

 

 

Before sorting by student ID

 

 

 

Student-ID

Name

CGPA (for 4.0)

 

 

[

 

 

 

 

 

cs011

Lennon

 

3.1,

 

 

cs021

McCartney

3.4,

 

 

cs012

Harrison

 

2.7,

 

 

cs022

Starr

 

3.7]

 

 

After sorting by student ID

 

 

 

Student-ID

Name

CGPA (for 4.0)

 

 

[

 

 

 

 

 

cs011

Lennon

 

3.1,

 

 

cs012

Harrison

 

2.7,

 

 

cs021

McCartney

3.4,

 

 

cs022

Starr

 

3.7]

 

 

 

 

 

 

 

You have implemented the Comparable<Student> interface. When you call the sort() method, it calls the compareTo() method to compare Student objects by their IDs. Since Student IDs are unique, it is a natural comparison order that works well.

Now, you may need to arrange students based on the cumulative grade point average (CGPA) they got. You may even need to compare Students based on their names. If you need to implement two or more alternative ways to

compare two similar objects, then you may implement the Comparator class. Listing 6-24 is an implementation (there is no change in the Student class, so we are not producing it here again).

190

Chapter 6 Generics and Collections

Listing 6-24.  ComparatorTest2.java

// This program shows the implementation of Comparator interface

import java.util.*;

class CGPAComparator implements Comparator<Student> { public int compare(Student s1, Student s2) { return (s1.cgpa.compareTo(s2.cgpa));

}

}

class ComparatorTest {

public static void main(String []args) {

Student []students = { new Student("cs011", "Lennon ", 3.1), new Student("cs021", "McCartney", 3.4),

new Student("cs012", "Harrison ", 2.7), new Student("cs022", "Starr ", 3.7) };

System.out.println("Before sorting by CGPA "); System.out.println("Student-ID \t Name \t CGPA (for 4.0) "); System.out.println(Arrays.toString(students));

 

 

 

 

Arrays.sort(students, new CGPAComparator());

 

 

 

 

System.out.println("After sorting by CGPA");

 

System.out.println("Student-ID \t Name \t CGPA (for 4.0) ");

 

System.out.println(Arrays.toString(students));

}

 

 

 

}

 

 

 

 

 

 

It prints the following:

 

 

 

 

 

Before sorting by CGPA

 

 

Student-ID

Name

CGPA (for 4.0)

[

 

 

 

cs011

Lennon

 

3.1,

cs021

McCartney

3.4,

cs012

Harrison

 

2.7,

cs022

Starr

 

3.7]

After sorting by CGPA

 

 

Student-ID

Name

CGPA (for 4.0)

[

 

 

 

cs012

Harrison

 

2.7,

cs011

Lennon

 

3.1,

cs021

McCartney

3.4,

cs022

Starr

 

3.7]

 

 

 

Yes, the program prints the Student data sorted by their CGPA. You didn’t change the Student class; the class still implements the Comparable<String> interface and defines the compareTo() method, but you don’t use the compareTo() method in your program. You create a separate class named CGPAComparator and implement the Comparator<Student> interface. You define the compare() method, which takes two Student objects as arguments.

191

Соседние файлы в предмете [НЕСОРТИРОВАННОЕ]