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

Chapter 6 Generics and Collections

Listing 6-20.  NavigableMapTest.java

// This program demonstrates the usage of navigable tree interface and TreeMap class

import java.util.*;

public class NavigableMapTest {

public static void main(String []args) {

NavigableMap<Integer, String> examScores = new TreeMap<Integer, String>();

examScores.put(90, "Sophia"); examScores.put(20, "Isabella"); examScores.put(10, "Emma"); examScores.put(50, "Olivea");

System.out.println("The data in the map is: " + examScores); System.out.println("The data descending order is: " + examScores.descendingMap()); System.out.println("Details of those who passed the exam: " +

examScores.tailMap(40));

System.out.println("The lowest mark is: " + examScores.firstEntry());

}

}

It prints the following:

The data in the map is: {10=Emma, 20=Isabella, 50=Olivea, 90=Sophia}

The data descending order is: {90=Sophia, 50=Olivea, 20=Isabella, 10=Emma} Details of those who passed the exam: {50=Olivea, 90=Sophia}

The lowest mark is: 10=Emma

In this program, you have a NavigableMap<Integer, String> that maps the exam score and the name of the person. You create a TreeMap<String, String> to actually store the exam scores. By default, a TreeMap stores data in ascending order. If you want the data in descending order, it’s easy: you just have to use the descendingMap() method (or descendingKeySet() if you are only interested in the keys).

Given the passing score is 40, you might want to get the map with data of those who failed in the exam. For that, you can use the headMap() method with the key value 40 (since the data is in ascending order, you want to get the “head” part of the map from the given position). Similarly, to get the data of those who passed the exam, you can use the tailMap() method.

If you want the immediate ones above and below the passing score, you can use the higherEntry() and lowerEntry() methods, respectively. The firstEntry() and lastEntry() methods give the entries with lowest and highest key values. So, when you use the firstEntry() method on examScores, you get Emma with 10 marks. If you use lastEntry(), you get Sophia, who has score 90.

The Queue Interface

A Queue follows FIFO mechanism: the first inserted element will be removed first. For getting a queue behavior, you can create a LinkedList object and refer it through a Queue reference. When you call the methods from Queue reference, the object behaves like a Queue. Listing 6-21 shows an example and it will become clear. Lennon,

McCartney, Harrison, and Starr are taking an online exam. Let’s see how you can remember the sequence in which they logged in to take the exam (see Listing 6-21).

185

Chapter 6 Generics and Collections

Listing 6-21.  QueueTest.java

// This program shows the key characteristics of Queue interface

import java.util.*;

class QueueTest {

public static void main(String []args) {

Queue<String> loginSequence = new LinkedList<String>();

loginSequence.add("Harrison");

loginSequence.add("McCartney");

loginSequence.add("Starr");

loginSequence.add("Lennon");

System.out.println("The login sequence is: " + loginSequence); while(!loginSequence.isEmpty())

System.out.println("Removing " + loginSequence.remove());

}

}

This prints the following:

The login sequence is: [Harrison, McCartney, Starr, Lennon] Removing Harrison

Removing McCartney Removing Starr Removing Lennon

In this example, you create a Queue<String> to point it to a LinkedList<String> object. Then you add four elements (names in the sequence in which they logged in) to the queue. After the elements are inserted, you print the queue by (implicitly) calling the toString() method on loginSequence. You call the remove() method to remove one element of the queue. The remove() method removes an element from the head of the queue and returns the extracted element. You got the same sequence as output as you inserted in the queue.

The Deque Interface

Deque (Doubly ended queue) is a data structure that allows you to insert and remove elements from both the ends. The Deque interface was introduced in Java 6 in java.util.collection package. The Deque interface extends the Queue interface just discussed. Hence, all methods provided by Queue are also available in the Deque interface. Let’s examine the commonly used methods of the Deque interface, summarized in Table 6-7.

186

Chapter 6 Generics and Collections

Table 6-7.  Commonly Used Methods in the Deque Interface

 

 

Method

Short Description

void addFirst(Element)

Adds the Element to the front of the Deque.

void addLast(Element)

Adds the Element to the last of the Deque.

Element removeFirst()

Removes an element from the front of the Deque and returns it.

Element removeLast()

Removes an element from the last of the Deque and returns it.

Element getFirst()

Returns the first element from the Deque, does not remove.

Element getLast()

Returns the last element from the Deque, does not remove.

 

 

All methods listed in Table 6-7 raise appropriate exceptions if they fail. There is another set of methods, listed in Table 6-8, that achieves the same functionality. However, they do not raise exception on failure; instead they return a special value. For instance, the method getFirst() returns the first element from the Deque but does not remove it. If the Deque is empty, it raises the exception, NoSuchElementException. At the same time, the peekFirst() method also carry out the same functionality. However, it returns null if the Deque is empty. When the Deque is created with predefined capacity, the methods listed in Table 6-8 are preferred over the methods listed in Table 6-7.

Table 6-8.  Commonly Used Methods in the Deque Interface (Returns Special Value)

 

 

Method

Short Description

boolean offerFirst(Element)

Adds the Element to the front of the Deque if it is not violating capacity constraint.

boolean offerLast(Element)

Adds the Element to the end of the Deque if it is not violating capacity constraint.

Element pollFirst()

Removes an element from the front of the Deque and returns it; if the Deque is

 

empty, it returns null.

Element pollLast()

Removes an element from the end of the Deque and returns it; if the Deque is

 

empty, it returns null.

Element peekFirst()

Returns the first element from the Deque but does not remove it; returns null

 

if Deque is empty.

Element peekLast()

Returns the last element from the Deque but does not remove it; returns null

 

if Deque is empty.

 

 

You just observed that the methods in Table 6-8 return null if they fail. What if you are storing null as an element? Well, it is not recommended that you store null as an argument, since there are methods in the Deque interface that return null, and it would be difficult for you to distinguish between the success or failure of the method call.

There are three concrete implementations of the Deque interface: LinkedList, ArrayDeque, and LinkedBlockingDeque. Let’s use ArrayDeque to understand the features of the Deque interface.

187

Chapter 6 GeneriCs and ColleCtions

It is evident from the list of methods supported by Deque that it is possible to realize the standard behavior of a queue, stack, and deque. Let’s implement a special queue (say, to pay utility bill) where a customer can be added only at the end of the queue and can be removed either at the front of the queue (when the customer paid the bill) or from the end of the queue (when the customer gets frustrated from the long line and leaves the queue himself). Listing 6-22 shows how to do this.

Listing 6-22. SplQueueTest.java

// This program shows the usage of Deque interface

import java.util.*;

class SplQueue {

private Deque<String> splQ = new ArrayDeque<>(); void addInQueue(String customer){

splQ.addLast(customer);

}

void removeFront(){ splQ.removeFirst();

}

void removeBack(){ splQ.removeLast();

}

void printQueue(){

System.out.println("Special queue contains: " + splQ);

}

}

class SplQueueTest {

public static void main(String []args) { SplQueue splQ = new SplQueue(); splQ.addInQueue("Harrison"); splQ.addInQueue("McCartney"); splQ.addInQueue("Starr"); splQ.addInQueue("Lennon");

splQ.printQueue();

splQ.removeFront();

splQ.removeBack();

splQ.printQueue();

}

}

It prints the following:

Special queue contains: [Harrison, McCartney, Starr, Lennon]

Special queue contains: [McCartney, Starr]

You first define a class—SplQueue—that defines a container splQ of type ArrayDeque with basic four operations. The method addInQueue() adds a customer at the end of the queue, the method removeBack() removes a customer from the end of the queue, the method removeFront() removes a customer from the front of the queue, and the method printQueue() simply prints all elements of the queue. You simply use the addLast(), removeFront(),

188

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