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

Chapter 6 Generics and Collections

You compare the CGPA of the arguments s1 and s2 by (re)using the compareTo() method from the Double class. You didn’t change anything in the main() method except for the way you call the sort() method. You create a new CGPAComparator() object and pass as the second argument to the sort() method. By default sort() uses the

compareTo() method; since you are passing a Comparator object explicitly, it now uses the compare() method defined in the CGPAComparator. So, the Student objects are now compared and sorted based on their CGPA.

You’ve learned quite a lot about the differences between the Comparable and Comparator interfaces, summarized in Table 6-9.

Table 6-9.  Differences between Implementing Comparable and Comparator Interfaces

Comparable Interface

Comparator Interface

Used when the objects need to be compared in their natural order.

You do not create a separate class just to implement the Comparable interface.

For a given class type, you have only that class (and that class alone) implementing the Comparable interface.

The method in the Comparable interface is declared as int compareTo(ClassType type);.

Used when the objects need to be compared in custom user-defined order (other than the natural order).

You create a separate class just to implement the Comparator interface.

You can have many separate (i.e., independent) classes implementing the Comparator interface, with each class defining different ways to compare objects.

The method in the Comparator interface is declared as int compare(ClassType type1, ClassType type2);.

Most classes have a natural order for comparing objects, so implement the Comparable interface for your classes in those cases. If you want to compare the objects other than the natural order or if there is no natural ordering present for your class type, then create separate classes implementing the Comparator interface.

Algorithms (Collections Class)

You’ve seen two important components of the collections framework: abstract classes/interfaces and the concrete class implementations. The collections framework also has a utility class named Collections (note the suffix “s” in the class name). It provides algorithms that are useful for manipulating data structures provided in the collections framework. You’ll see important methods like sort(), binarySearch(), reverse(), shuffle(), etc., in this short section (check Table 6-10).

192

Chapter 6 Generics and Collections

Table 6-10.  Important Algorithms (Static Methods in the Collections Class)

Method

Short Description

int binarySearch(List<? extends Comparable<? super T>> list, T key)

void copy(List<? super T> dest, List<? extends T> src)

Looks for the key in List. If found, it returns a value >= 0; otherwise it returns a negative value. It has an overloaded version that also takes a Comparator object for comparing elements.

Copies all the elements from src List to dest List.

void fill(List<? super T> list, T obj)

T max(Collection<? extends T> coll)

Fills the whole list with the value obj.

Returns the max element in the list. It has an overloaded version that also takes a Comparator object for comparing elements.

T min(Collection<? extends T> coll)

Returns the min element in the list. It has an overloaded version that also takes a Comparator object for comparing elements.

boolean replaceAll(List<T> list,

Replaces all occurrences of oldVal with newVal in list.

T oldVal, T newVal)

 

void reverse(List<?> list)

Reverses all the elements in the given list.

void rotate(List<?> list, int distance)

Rotates the list given by the value distance.

void shuffle(List<?> list)

Shuffles elements in the list randomly.

void sort(List<T> list)

Sorts the list in its natural order (i.e., by using the compareTo()

 

method). It has an overloaded version that also takes a

 

Comparator object for comparing elements.

void swap(List<?> list, int i, int j)

Swaps the elements in the positions i and j in the list.

 

 

Assume that you are creating a playlist of your favorite Michael Jackson songs. There are many things that you can do with a playlist: you can sort, shuffle, search, reverse, or replay songs. Let’s do all these in a PlayList program (see Listing 6-25).

Listing 6-25.  PlayList.java

// This program demonstrates some of the useful methods in Collections class

import java.util.*;

class PlayList {

public static void main(String []args) {

// let's create a list of some Michael Jackson's songs List<String> playList = new LinkedList<String>(); playList.add("Rock With You - 1979"); playList.add("Billie Jean - 1983");

playList.add("Man In the Mirror - 1988"); playList.add("Black Or White - 1991");

System.out.println("The original playlist of MJ's songs"); System.out.println(playList);

193

Chapter 6 Generics and Collections

System.out.println("\nThe reversed playlist"); Collections.reverse(playList); System.out.println(playList);

System.out.println("\nNow after shuffling the playlist"); Collections.shuffle(playList); System.out.println(playList);

System.out.println("\nSort the songs by their names "); Collections.sort(playList); System.out.println(playList);

System.out.println("\nIs my most favourite song Black Or White - 1991 present in the list?");

String backOrWhiteSong = "Black Or White - 1991";

int index = Collections.binarySearch(playList, backOrWhiteSong); if(index >= 0)

System.out.printf("Yes, its the %d song \n", (index + 1));

else

System.out.printf("No, its not there in the playlist \n");

System.out.println("\nLet me forward by two songs (rotate the list) "); Collections.rotate(playList, 2);

System.out.println(playList);

}

}

It prints the following:

The original playlist of MJ's songs

[Rock With You - 1979, Billie Jean - 1983, Man In the Mirror - 1988, Black Or White - 1991]

The reversed playlist

[Black Or White - 1991, Man In the Mirror - 1988, Billie Jean - 1983, Rock With You - 1979]

Now after shuffling the playlist

[Black Or White - 1991, Man In the Mirror - 1988, Rock With You - 1979, Billie J ean - 1983]

Sort the songs by their names

[Billie Jean - 1983, Black Or White - 1991, Man In the Mirror - 1988, Rock With You - 1979]

Is my most favourite song Black Or White - 1991 present in the list? Yes, its the 2 song

Let me forward by two songs (rotate the list)

[Man In the Mirror - 1988, Rock With You - 1979, Billie Jean - 1983, Black Or White - 1991]

194

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