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

Chapter 6 Generics and Collections

In this program, you use a LinkedList of Characters to store each character in the input string. Why LinkedList<Character> instead of LinkedList<char>? The container classes store references to objects, so you cannot use primitive types with any of the collection classes. Since you have wrapper classes and auto-boxing, it is not a big problem—that is why you use Character instead of char here.

Also note how you assign LinkedList<Character> to List<Character>. Since the LinkedList class implements the List interface, you can do this assignment. Using Collection interfaces instead of concrete class types for holding references is a good programming practice, since—if you want to change LinkedList to an ArrayList in future—the change is very easy if you use the List interface for reference. Now back to the program.

The method toCharArray() in String returns a char[], and you use a for each loop to traverse each character in that array. As the loop executes, you put the characters into the linked list. Now how do you traverse the linked list in both directions?

You can use the methods hasNext() and next() to traverse the forward and methods of hasPrevious() and previous() in ListIterator for moving in the reverse direction. How do you get the ListIterator from the

LinkedList? You have a method listIterator() and listIterator(index) in the List interface. Since you want to traverse the LinkedList in both directions, you use both listIterator() and listIterator(index) methods. In the first case, you get the iterator referring to beginning of the container; in another case, you pass the length of

the string as an argument to the listIterator method to get the reverse iterator. Once you get both the iterators, it is straightforward to use hasNext() and next() on the first iterator and the hasPrevious() and previous() methods on the second iterator.

The Set Interface

Set, as we studied in our math classes in high school, contains no duplicates. Unlike List, a Set doesn’t remember where you inserted the element (i.e., it doesn’t remember the insertion order).

There are two important concrete classes for Set: HashSet and TreeSet. A HashSet is for quickly inserting and retrieving elements; it does not maintain any sorting order for the elements it holds. A TreeSet stores the elements in a sorted order (and it implements the SortedSet interface).

The HashSet Class

Given a sentence, how can you remove repeated words in that sentence? Set does not allow duplicates, and HashSet can be used for quick insertion and search. So you can use a HashSet for solving this problem (see Listing 6-16).

Listing 6-16.  RemoveDuplicates.java

// This program demonstrates the usage of HashSet class

import java.util.*;

class RemoveDuplicates {

public static void main(String []args) {

String tongueTwister = "I feel, a feel, a funny feel, a funny feel I feel, if you feel the feel I feel, I feel the feel you feel";

Set<String> words = new HashSet<>();

// split the sentence into words and try putting them in the set for(String word : tongueTwister.split("\\W+"))

words.add(word);

179

Chapter 6 Generics and Collections

System.out.println("The tongue twister is: " + tongueTwister); System.out.print("The words used were: "); System.out.println(words);

}

}

It prints the following:

The tongue twister is: I feel, a feel, a funny feel, a funny feel I feel, if you feel the feel I feel, I feel the feel you feel

The words used were: [feel, if, a, funny, you, the, I]

In this example, the tongue twister sentence has only two word separators—comma and white space. You split the string using these separators by using the split() method. The split() method takes a regular expression as an argument (regular expressions are covered in Chapter 7). The regular expression \\W+ means it is for splitting on word boundaries. So, the string is separated into words, ignoring the punctuation marks like commas.

You try to insert each word into the set. If the word already exists, the add() method fails and returns false (you are not storing this return value). Once you insert all elements in the HashSet, you print them one by one and find that the tongue twister with 25 words used only 7 words!

The TreeSet Class

Given a sentence, how can you sort the letters used in that sentence into alphabetical order? A TreeSet puts the values in a sorted order, so you can use a TreeSet container for solving this problem (see Listing 6-17).

Listing 6-17.  TreeSetTest.java

// This program demonstrates the usage of TreeSet class

import java.util.*;

class TreeSetTest {

public static void main(String []args) {

String pangram = "the quick brown fox jumps over the lazy dog"; Set<Character> aToZee = new TreeSet<Character>();

for(char gram : pangram.toCharArray()) aToZee.add(gram);

System.out.println("The pangram is: " + pangram); System.out.print("Sorted pangram characters are: " + aToZee);

}

}

It prints the following:

The pangram is: the quick brown fox jumps over the lazy dog

Sorted pangram characters are: [ , a, b, c, d, e, f, g, h, i, j, k, l, m, n, o, p, q, r, s, t, u, v, w, x, y, z]

A pangram is a sentence that uses all letters in the alphabet at least once. You want to store characters of a pangram in the set. Since you need to use reference types for containers, you’ve created a TreeSet of Characters.

180

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