Добавил:
Upload Опубликованный материал нарушает ваши авторские права? Сообщите нам.
Вуз: Предмет: Файл:

AhmadLang / Java, How To Program, 2004

.pdf
Скачиваний:
626
Добавлен:
31.05.2015
Размер:
51.82 Mб
Скачать

[Page 950 (continued)]

19.13. Unmodifiable Collections

The Collections API provides a set of static methods that create unmodifiable wrappers for collections. Unmodifiable wrappers throw UnsupportedOperationExceptions if attempts are made to modify the collection. Headers for these methods are listed in Fig. 19.23. Details about these methods are available at java.sun.com/j2se/5.0/docs/api/java/util/Collections.html. All these methods take a generic type and return an unmodifiable view of the generic type. For example, the following code creates an unmodifiable List (list2) that stores String objects:

List< String > list1 = new ArrayList< String >();

List< String > list2 = Collections.unmodifiableList( list1 );

Figure 19.23. Unmodifiable wrapper methods.

(This item is displayed on page 951 in the print version)

public static method headers

<

T

>

Collection< T > unmodifiableCollection( Collection< T > c )

<

T

>

List< T > unmodifiableList( List< T > aList )

<

T

>

Set< T > unmodifiableSet( Set< T > s )

< T > SortedSet<

T

>

unmodifiableSortedSet( SortedSet< T > s

)

<

K,

V

>

Map< K,

V

>

unmodifiableMap( Map< K, V >

m )

 

<

K,

V

>

SortedMap<

 

K, V > unmodifiableSortedMap(

SortedMap<

K, V > m )

Software Engineering Observation 19.5

You can use an unmodifiable wrapper to create a collection that offers read-only access to others, while allowing readwrite access to yourself. You do this simply by giving others a reference to the unmodifiable wrapper while retaining for yourself a reference to the original collection.

[Page 950 (continued)]

19.14. Abstract Implementations

The collections framework provides various abstract implementations of Collection interfaces from which the programmer can quickly "flesh out" complete customized implementations. These abstract implementations include a thin Collection implementation called an AbstractCollection, a thin List implementation that allows random access to its elements called an AbstractList, a thin Map implementation called an AbstractMap, a thin List implementation that allows sequential access to its elements called an AbstractSequentialList, a thin Set implementation called an

AbstractSet and a thin Queue implementation called AbstractQueue. You can learn more about these classes at java.sun.com/j2se/5.0/docs/api/java/util/package-summary.html.

[Page 951]

To write a custom implementation, you can extend the abstract implementation class that best meets your needs, and implement each of the class's abstract methods. Then, if your collection is to be modifiable, override any concrete methods that prevent modification.

[Page 951 (continued)]

19.15. Wrap-Up

This chapter introduced the Java collections framework. You learned how to use class Arrays to perform array manipulations. You learned the collection hierarchy and how to use the collections framework interfaces to program with collections polymorphically. You also learned several predefined algorithms for manipulating collections. In the next chapter, we introduce Java applets, which are Java programs that typically execute in a Web browswer. We start with sample applets that come with the JDK, then show you how to write and execute your own applets.

[Page 951 (continued)]

Summary

The Java collections framework gives the programmer access to prepackaged data structures as well as to algorithms for manipulating them.

A collection is an object that can hold references to other objects. The collection interfaces declare the operations that can be performed on each type of collection.

The classes and interfaces of the collections framework are in package java.util.

Class Arrays provides static methods for manipulating arrays, including sort for sorting an

array, binarySearch for searching a sorted array, equals for comparing arrays and fill for placing items in an array.

Arrays method asList returns a List view of an array, which enables a program to manipulate

the array as if it were a List. Any modifications made through the List view change the array, and any modifications to the array change the List view.

[Page 952]

Method size gets the number of items in a List, and method get returns a List element.

Interface Collection is the root interface in the collection hierarchy from which interfaces Set

and List are derived. Interface Collection contains bulk operations for adding, clearing, comparing and retaining objects in a collection. Interface Collection provides a method iterator for getting an Iterator.

Class Collections provides static methods for manipulating collections. Many of the methods are implementations of polymorphic algorithms for searching, sorting and so on.

A List is an ordered Collection that can contain duplicate elements.

Interface List is implemented by classes ArrayList, LinkedList and Vector. Class ArrayList is a resizable-array implementation of a List. A LinkedList is a linked-list implementation of a

List.

Iterator method hasNext determines whether a Collection contains another element. Method next returns a reference to the next object in the Collection and advances the Iterator.

Method subList returns a view of a portion of a List. Any changes made to this view are also made to the List.

Method clear removes elements from a List.

Method toArray returns the contents of a collection as an array.

Class Vector manages dynamically resizable arrays. At any time, a Vector contains a number of

elements that is less than or equal to its capacity. If a Vector needs to grow, it grows by its capacity increment. If no capacity increment is specified, Java doubles the size of the Vector each time additional capacity is required. The default capacity is 10 elements.

Vector method add adds its argument to the end of the Vector. Method insertElementAt inserts an element at the specified position. Method set sets the element at a specific position.

Vector method remove removes the first occurrence of its argument from the Vector. Method

removeAllElements removes every element from the Vector. Method removeElementAt removes the element at the specified index.

Vector method firstElement returns a reference to the first element. Method lastElement returns a reference to the last element.

Vector method contains determines whether the Vector contains the searchKey specified as an

argument. Vector method indexOf gets the index of the first location of its argument. The method returns 1 if the argument is not found in the Vector.

Vector method isEmpty determines whether the Vector is empty. Methods size and capacity

determine the number of elements currently in the Vector and the number of elements that can be stored in the Vector without allocating more memory, respectively.

Algorithms sort, binarySearch, reverse, shuffle, fill and copy operate on Lists. Algorithms

min and max operate on Collections. Algorithm reverse reverses the elements of a List, fill sets every List element to a specified Object, and copy copies elements from one List into another List. Algorithm sort sorts the elements of a List.

Algorithms addAll appends all the elements in an array to a collection, frequency calculates

how many elements in the collection are equal to the specified element, and disjoint determines whether two collections have elements in common.

Algorithms min and max find the smallest and largest items in a collection.

The Comparator interface provides a means of sorting a Collection's elements in an order other than their natural order.

Collections method reverseOrder returns a Comparator object that can be used with sort to sort elements of a collection in reverse order.

[Page 953]

Algorithm shuffle randomly orders the elements of a List.

Algorithm binarySearch locates an Object in a sorted List.

Class Stack extends Vector. Stack method push adds its argument to the top of the stack.

Method pop removes the top element of the stack. Method peek returns a reference to the top element without removing it. Stack method empty determines whether the stack is empty.

Queue, a new collection interface introduced in J2SE 5.0, extends interface Collection and provides additional operations for inserting, removing and inspecting elements in a queue.

PriorityQueue, one of the Queue implementations, orders elements by their natural ordering

(i.e., the implementation of the compareTo method) or by a Comparator object that is supplied through the constructor.

The common PriorityQueue operations are offer to insert an element at the appropriate

location based on priority order, poll to remove the highest-priority element of the priority queue (i.e., the head of the queue), peek to get a reference to the highest-priority element of the priority queue, clear to remove all elements in the priority queue and size to get the number of elements in the priority queue.

A Set is a Collection that contains no duplicate elements. HashSet stores its elements in a hash table. treeSet stores its elements in a tree.

Interface SortedSet extends Set and represents a set that maintains its elements in sorted order. Class TReeSet implements SortedSet.

TReeSet method headSet gets a view of a treeSet that is less than a specified element. Method tailSet gets a view that is greater than or equal to a specified element. Any changes made to

the view are made to the TReeSet.

Maps map keys to values and cannot contain duplicate keys. Maps differ from Sets in that Maps

contain both keys and values, whereas Sets contain only values. HashMaps store elements in a hash table, and treeMaps store elements in a tree.

Hashtables and HashMaps store elements in hash tables, and treeMaps store elements in trees.

HashMap is a generic class that takes two type arguments. The first type argument specifies the type of key, and the second type argument specifies the type of value.

HashMap method put adds a key and a value into a HashMap. Method get locates the value associated with the specified key. Method isEmpty determines whether the map is empty.

HashMap method keySet returns a set of the keys. Map methods size and isEmpty returns the

number of key-value pairs in the Map and a boolean indicating whether the Map is empty, respectively.

Interface SortedMap extends Map and represents a map that maintains its keys in sorted order. Class treeMap implements SortedMap.

A Properties object is a persistent Hashtable object. Class Properties extends Hashtable.

The Properties no-argument constructor creates an empty Properties table with no default

properties. There is also an overloaded constructor that is passed a reference to a default Properties object containing default property values.

Properties method setProperty specifies the value associated with the key argument.

Properties method getProperty locates the value of the key specified as an argument. Method store saves the contents of the Properties object to the OutputStream object specified as the first argument. Method load restores the contents of the Properties object from the InputStream object specified as the argument.

[Page 954]

Collections from the collections framework are unsynchronized. Synchronization wrappers are provided for collections that can be accessed by multiple threads.

The Collections API provides a set of public static methods for converting collections to

unmodifiable versions. Unmodifiable wrappers throw UnsupportedOperationExceptions if attempts are made to modify the collection.

The collections framework provides various abstract implementations of collection interfaces from which the programmer can quickly flesh out complete customized implementations.

[Page 954 (continued)]

Terminology

AbstractCollection class

AbstractList class

AbstractMap class

AbstractQueue class

AbstractSequentialList class

AbstractSet class

add method of List

add method of Vector

addAll method of Collections

addFirst method of List

addLast method of List

algorithms in Collections

ArrayList

array

arrays as collections asList method of Arrays bidirectional iterator

binarySearch method of Arrays binarySearch method of Collections capacity increment of a Vector capacity method of Vector

clear method of List

clear method of PriorityQueue

collection

Collection interface

Collections class

collections framework

collections placed in arrays

collision in hashing

contains method of Vector

containsKey method of HashMap

Comparable interface

Comparator interface

compareTo method of Comparable copy method of Collections delete an element from a collection disjoint method of Collections duplicate elements

fill method of Arrays

fill method of Collections firstElement method of Vector frequency method of Collections get method of HashMap

getProperty method of class Properties

hashing

HashMap class

HashSet class

Hashtable class

hasMoreTokens method of StringTokenizer hasNext method of Iterator

hasPrevious method of ListIterator insert an element into a collection indexOf method of Vector

isEmpty method of Map isEmpty method of Vector

iterate through container elements

iterator

Iterator interface

key in HashMap

keySet method of HashMap

key/value pair

lastElement method of Vector

lexicographical comparison

LinkedList class

List interface

ListIterator interface load factor in hashing map

Map collection interface mapping keys to values mappings

max method of Collections min method of Collections modifiable collections natural comparison method natural ordering

next method of Iterator

nextToken method of StringTokenizer

NoSuchElementException class

offer method of PriorityQueue

[Page 955]

one-to-one mapping ordered collection ordering

peek method of PriorityQueue

peek method of Stack

poll method of PriorityQueue

pop method of Stack

PriorityQueue class

Properties class

put method of HashMap

Queue interface

range-view methods

removeAllElements method of Vector removeElement method of Vector removeElementAt method of Vector reverse method of Collections reverseOrder method of Collections sequence

Set interface

shuffle method of Collections size method of List

size method of PriorityQueue sort a List

sort method of Arrays

sort method of Collections SortedMap collection interface

SortedSet collection interface

stable sort

Stack class

StringTokenizer class synchronization wrappers

TReeMap class treeSet class