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

Chapter 6 Generics and Collections

Just spend a couple of minutes looking at the output against the program and make sure you understand it. Okay, let’s see what’s happening.

1.You create a LinkedList<String> with four MJ songs.

2.You print the contents of the list; it prints the songs in the order in which you inserted them.

3.The Collections.reverse() method reverses the contents of the given List. So, you have the songs in the reverse order.

4.Next, you shuffle the List using Collections.shuffle()—the songs are in different positions now. You sort the songs by their names. Since the songs are Strings, the songs are now sorted in alphabetical order.

5.You search for your favorite song in the playlist using the Collections.binarySearch() method. This method takes two arguments, the List and the key you are searching for. If the key is found, the int value will be >= 0 and that value is the index of the key in the List. If it is negative, it means the value is not found. You found the song you searched for.

6.You rotate the sorted play list by two positions using the Collections.rotate() method. It takes two arguments, the List and an int value, to tell how many positions you need to move the values.

The Arrays Class

Similar to Collections, Arrays is also a utility class (i.e., the class has only static methods). Methods in Collections are also very similar to methods in Arrays. The Collections class is for container classes; the Arrays class is for native arrays (i.e., arrays with [] syntax).

Methods in the Arrays Class

Listing 6-26 is a trivial example to show why the Arrays class is very useful for working with native arrays. Can you tell what this program prints?

Listing 6-26.  PrintArray.java

// This code implements a simple integer array

class PrintArray {

public static void main(String []args) { int [] intArray = {1, 2, 3, 4, 5};

System.out.println("The array contents are: " + intArray);

}

}

It prints the following:

The array contents are: [I@3e25a5

195

Chapter 6 Generics and Collections

What went wrong? The println() implicitly calls the toString() method of the native int[] array. Native arrays are not classes, though they inherit the Object class, so it is not possible to override methods like toString(). (Remember that overriding can be done only in classes.) In other words, intArray.toString() is called where the toString() method is inherited from Object. So, how do you print the contents of a native array?

Fortunately, you have the Arrays utility class that has methods like toString(). Listing 6-27 is the correct program for printing the contents of a native array.

Listing 6-27.  PrintArray2.java

// This program demonstrates the usage of Arrays class

import java.util.*;

class PrintArray {

public static void main(String []args) { int [] intArray = {1, 2, 3, 4, 5};

System.out.println("The array contents are: " + Arrays.toString(intArray));

}

}

Now the output is as expected:

The array contents are: [1, 2, 3, 4, 5]

Use the Arrays.toString() method to print the contents of the array instead of using Object’s toString() method! As you can see, the methods in the Arrays class can be handy. Now, you’ll look at methods like sort(), binarySearch(), etc. Table 6-11 lists important methods in the Arrays class.

Table 6-11.  Important (Static) Methods in the Arrays Class

Method

Description

List<T> asList(T . . . a)

Creates a fixed-size List out of the given array.

int binarySearch(Object[] objArray,

Search for key in objArray. Returns an int value >= (index of the key)

Object key)

if found; otherwise it returns a negative value. Overloads available for

 

primitive types like int[], byte[], etc. Also, overload available for taking

 

a Comparator object.

boolean equals(Object[] objArray1,

Checks if the contents of objArray1 and objArray2 are equal. Overloads

Object[] objArray2)

available for primitive type arrays like int[], byte[], etc.

void fill(Object[] objArray, Object val)

Fills the objArray with value val. Overloads available for primitive type

 

arrays like int[], byte[], etc.

void sort(Object[] objArray)

Sorts the objArray based on the natural order (i.e., using the

 

compareTo() method). Overloads available for primitive type arrays like

 

int[], byte[], etc. Also an overload is available for taking a Comparator

 

object.

String toString(Object[] a)

Returns the String representation of the given objArray. Overloads

 

available for primitive type arrays like int[], byte[], etc.

 

 

196

Chapter 6 Generics and Collections

The Arrays.sort(Object []) calls the compareTo() method to compare the elements. So, the array elements passed to sort must implement the Comparable interface. The sort method is overloaded for primitive types (like byte[], int[] etc). For the elements, the sorting is done in ascending numeric order. Listing 6-28 calls the sort() method on a String array and an int array.

Listing 6-28.  CollectionsTest.java

// It demonstrates sorting on Arrays class CollectionsTest {

public static void main(String []args) {

String [] strArr = { "21", "1", "111", "12", "123" }; Arrays.sort(strArr); System.out.println(Arrays.toString(strArr));

int [] intArr = { 21, 1, 111, 12, 123 }; Arrays.sort(intArr); System.out.println(Arrays.toString(intArr));

}

}

It prints the following:

[1, 111, 12, 123, 21] [1, 12, 21, 111, 123]

The contents of the arrays look similar, but the output looks different. Why? This shows the difference in the sort done for strings and primitive types. The String's compareTo() method does lexicographic comparison—the string contents are compared character-by-character. This makes sense, for example, if you have strings like “john”, “johannes”, “johann”, “johnny”, etc. However, for numbers, you need to compare values. For this reason, after “1” comes “111” and then “12” and so on with Strings, but 1, 12, 21, and so on with integers.

Be aware how the values are compared when using the sort() method. For example, numeric ­comparison is done for integers whereas lexicographic comparison is done for Strings.

You’ve tried sorting. Now you’ll attempt searching values in an array. What does the program in Listing 6-29 print?

Listing 6-29.  BinarySearchTest.java

// This program shows the usage of binary search

import java.util.*;

class BinarySearchTest {

public static void main(String []args) {

String [] strArr = { "21", "22", "11", "12", "13" }; System.out.println("The given strArr is: " + Arrays.toString(strArr));

197

Chapter 6 GeneriCs and ColleCtions

int index = Arrays.binarySearch(strArr, "22"); System.out.println("The index value is: " + index);

}

}

It prints the following:

The index value is: -6

What went wrong? The binarySearch method takes two arguments: the first is the array to be searched and the second is the key value to be searched. If it succeeds, it returns the index of the key element in the array. If the key value is not found, it returns a negative value. Now, the binarySearch() method expects that it is called on an already sorted array. Here, you forgot to call sort() before doing binary search, so the method failed. Listing 6-30 shows the improved code.

Listing 6-30. BinarySearchTest2.java

// This program shows the usage of binary search

import java.util.*;

class BinarySearchTest {

public static void main(String []args) {

String [] strArr = { "21", "22", "11", "12", "13" }; System.out.println("The given strArr is: " + Arrays.toString(strArr)); Arrays.sort(strArr);

System.out.println("strArr after sorting is: " + Arrays.toString(strArr)); int index = Arrays.binarySearch(strArr, "22");

System.out.println("The index value is: " + index);

}

}

It prints the following:

The given strArr is: [21, 22, 11, 12, 13] strArr after sorting is: [11, 12, 13, 21, 22] The index value is: 4

Note that array index starts from zero, so the index position of 22 is 4 (i.e., strArr[4] == “22”).

Make sure you always call binarySearch() on a sorted array/container. otherwise, you’ll get unpredictable results.

Array as a List

Assume that you have temperatures recorded in your place for a week’s time. How can you write a simple program that prints the maximum and minimum temperatures recorded?

198

Chapter 6 Generics and Collections

For storing temperatures, you can use an array. However, the Arrays class does not have the max() or min() methods. One way to avoid writing your own method is to convert the array into List using the asList method, and use the max() and min() methods in the Collections class (see Listing 6-31). Remember that the array should be a reference type (you cannot use the asList method for primitive type arrays).

Listing 6-31.  ArrayAsList.java

// This program demonstrates the usage of arrays as list

import java.util.*;

public class ArrayAsList {

public static void main(String []args) {

Double [] weeklyTemperature = {31.1, 30.0, 32.5, 34.9, 33.7, 27.8}; List<Double> temperatures = Arrays.asList(weeklyTemperature); System.out.println("Maximum temperature recorded was: " +

Collections.max(temperatures));

System.out.println("Minimum recorded was: " + Collections.min(temperatures));

}

}

This prints the following:

Maximum temperature recorded was: 34.9 Minimum recorded was: 27.8

Yes, it works. But you made a simple logical mistake. In this program, you have given temperatures of only six and not seven days. You can add one more value in the array, but shall you try adding it directly to the List<Double> that you got? Here is the code segment that tries to add an element in the List:

List<Double> temperatures = Arrays.asList(weeklyTemperature); temperatures.add(32.3);

Now you get the following:

Exception in thread "main" java.lang.UnsupportedOperationException at java.util.AbstractList.add(AbstractList.java:131)

at java.util.AbstractList.add(AbstractList.java:91) at ArrayAsList.main(ArrayAsList.java:13)

You cannot add elements to the list returned by the asList() method. A solution is to create a new List type object (say, an ArrayList object) yourself and add elements to that List, as in Listing 6-32.

Listing 6-32.  ArrayAsList2.java

// This program demonstrates the usage of arrays as list

import java.util.*;

class ArrayAsList{

public static void main(String []args) {

Double [] temperatureArray = {31.1, 30.0, 32.5, 34.9, 33.7, 27.8}; System.out.println("The original array is: " + Arrays.toString(temperatureArray));

199

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