Presentation is loading. Please wait.

Presentation is loading. Please wait.

Generics And Collection Interface

Similar presentations


Presentation on theme: "Generics And Collection Interface"— Presentation transcript:

1 Generics And Collection Interface

2 Generics At its core, the term generics means parameterized types. Parameterized types are important because they enable you to create classes, interfaces, and methods in which the type of data upon which they operate is specified as a parameter. A class, interface, or method that operates on a parameterized type is called generic, as in generic class or generic method. With generics, all casts are automatic and implicit.

3 // A simple generic class
// A simple generic class.Here, T is a type parameter that will be replaced by a real type when an object of type Gen is created. class Gen<T> { T ob; // declare an object of type T. The output produced by the program is shown here: Gen(T o) { Type of T is java . lang . Integer ob = o ; } . value: 8 8 T getob ( ) { Type of T is j ava . lang . String return ob; } value: Generics Test // Show type of T. void showType ( ) { System. out .println ( "Type of T is " + ob . getClass ( ) . getName ( ) ) ; } } // Demonstrate the generic class, class GenDemo { public static void main(String args [] ) { Gen< Integer > iOb; // Create a Gen reference for Integers. iOb = new Gen<Integer> ( 88 ) ; //to encapsulate the value 88 within an Integer object. iOb . showType ( ) ; // Show the type of data used by iOb . int v = iOb . getob ( ) ; // Get the value in iOb. Notice that //no cast is needed. System. out .println ( "value : " + v) ; System. out .println ( ) ; Gen<String> strOb = new Gen<String> ( "Generics Test"); // Create a Gen object for Strings. StrOb . showType ( ) ; // Show the type of data used by strOb. String str = strOb . getob () ; // Get the value of strOb. Again, notice that no cast is needed. System. out .println ( "value : " + str);

4 Here, T is the name of a type parameter
Here, T is the name of a type parameter. This name is used as a placeholder for the actual type .Thus, T is used within Gen whenever the type parameter is needed. Whenever a type parameter is being declared, it is specified within angle brackets< >. Because Gen uses a type parameter, Gen is a generic class, which is also called a parameterized type. T is used to declare an object called ob, as shown here: T ob; Thus, ob will be an object of the type passed to T. Now consider Gen's constructor: Gen(T o) { ob = o ; } Notice that its parameter, o, is of type T. This means that the actual type of o is determined by the type passed to T when a Gen object is created. The type parameter T can also be used to specify the return type of a method, as is the case with the getob( ) method, shown here: T getob ( ) { return ob; } Because ob is also of type T, its type is compatible with the return type specified by getob( ). The showType( ) method displays the type of T by calling getName( ) on the Class object returned by the call to getClass( ) on ob,which returns a string representation of the class name.

5 The GenDemo class demonstrates the generic Gen class
The GenDemo class demonstrates the generic Gen class. It first creates a version of Gen for integers, as shown here: Gen< Integer > iOb; In this case, Integer is a type argument that is passed to Gen's type parameter, T. Thus, for this declaration, ob is of type Integer, and the return type of getob ( ) is of type Integer. The line assigns to iOb a reference to an instance of an Integer version of the Gen class: iOb = new Gen<Integer> (88) ; Notice that when the Gen constructor is called, the type argument Integer is also specified. This is necessary .Thus, the reference returned by new must also be of type Gen<Integer>. If it isn't, a compile-time error will result. This type checking is one of the main benefits of generics because it ensures type safety.

6 Next, the program obtains the value of ob by use of the following line:
int v = iOb . getob () ; Because the return type of getob ( ) is T, which was replaced by Integer when iOb was declared, the return type of getob ( ) is also Integer, which unboxes into int when assigned to v (which is an int). Thus, there is no need to cast the return type of getob ( ) to Integer. Of course, it's not necessary to use the auto-unboxing feature. Next, GenDemo declares an object of type Gen<String>: Gen<String> strOb = new Gen<String> ( "Generics Test"); Because the type argument is String, String is substituted for T inside Gen. This creates (conceptually) a String version of Gen,

7 Generics Work Only with Objects
When declaring an instance of a generic type, the type argument passed to the type parameter must be a class type. You cannot use a primitive type, such as int or char. For example Gen<int> strOb = new Gen<int> (53 ) ; // Error, can't use primitive type Generic Types Differ Based on Their Type Arguments A key point to understand about generic types is that a reference of one specific version of a generic type is not type compatible with another version of the same generic type. For example, assuming the program just shown, the following line of code is in error and will not compile: iOb = strOb; // Wrong! Even though both iOb and strOb are of type Gen<T>, they are references to different types because their type parameters differ. This is part of the way that generics add type safety and prevent errors.

8 The Collections Framework

9 The Collections Framework
The Collections Framework is a sophisticated hierarchy of interfaces and classes that provide state-of-the-art technology for managing groups of objects. Prior to the Collections Framework, Java provided ad hoc classes such as Dictionary, Vector, Stack, and Properties to store and manipulate groups of objects. Although these classes were quite useful, they lacked a central, unifying theme. For example the way that you used Vector was different from the way that you used Properties. Collections are an answer to these (and other) problems.

10 Collection Overview The Collections Framework was designed to meet several goals. First, the framework had to be high-performance. Second, the framework had to allow different types of collections to work in a similar manner and with a high degree of interoperability. Third, extending and/ or adapting a collection had to be easy.

11 Mechanisms were added to the Collection framework that allow the integration of standard arrays into the Collections Framework. Algorithms are another important part of the collection mechanism. Algorithms operate on collections and are defined as static methods within the Collections class. The algorithms provide a standard means of manipulating collections. Another item closely associated with the Collections Framework is the Iterator interface. An iterator offers a general-purpose, standardized way of accessing the elements within a collection, one at a time. Thus, an iterator provides a means of enumerating the contents of a collection. In addition to collections, the framework defines several map interfaces and classes. Maps store key /value pairs. You can obtain a collection-view of a map Such a view contains the elements from the map stored in a collection.

12 The Collection Interfaces
The Collections Framework defines several interfaces, the collection interfaces is necessary because they determine the fundamental nature of the collection classes. Interface and their description Collection -Enables you to work with groups of objects; it is at the top of the collections hierarchy. Deque -Extends Queue to handle a double-ended queue. (Added by Java SE 6.) List -Extends Collection to handle sequences (lists of objects). NavigableSet- Extends SortedSet to handle retrieval of elements based on closest-match searches. (Added by Java SE 6.) Queue -Extends Collection to handle special types of lists in which elements are removed only from the head. Set -Extends Collection to handle sets, which must contain unique elements. SortedSet -Extends Set to handle sorted sets.

13 The Collection interface
The Collection interface is the foundation upon which the Collections Framework is built because it must be implemented by any class that defines a collection. Collection is a generic interface that has this declaration: interface Collection<E> Here, E specifies the type of objects that the collection will hold. Collection extends the Iterable interface. This means that all collections can be cycled through by use of the for-each style for loop. The collection interface consists of several methods which can throw following exceptions. UnsupportedOperationException : this occurs if a collection cannot be modified. ClassCastException : is generated when one object is incompatible with another, such as when an attempt is made to add an incompatible object to a collection. NullPointerException : is thrown if an attempt is made to store a null object and null elements are not allowed in the collection. IllegalArgumentException :is thrown if an invalid argument is used. IllegalStateException : is thrown if an attempt is made to add an element to a fixed-length collection that is full.

14 The Methods Defined by Collection
boolean add(E obj) :Adds obj to the invoking collection. Returns true if obj was added to the collection. Returns false if obj is already a member of the collection and the collection does not allow duplicates. boolean addAII(Collection<? extends E> c) :Adds all the elements of cto the invoking collection. Returns true if the operation succeeded (i.e., the elements were added). Otherwise, returns false. void clear( ) : Removes all elements from the invoking collection. boolean contains(Object obj) : Returns true if obj is an element of the invoking collection. Otherwise, returns false. boolean containsAII(Collection<?> c) : Returns true if the invoking collection contains all elements of c. Otherwise, returns false. boolean equals(Object obj) :Returns true if the invoking collection and obj are equal. Otherwise, returns false. int hashCode( ) : Returns the hash code for the invoking collection. boolean isEmpty( ) : Returns true if the invoking collection is empty. Otherwise, returns false. lterator<E> iterator( ) : Returns an iterator for the invoking collection. boolean remove(Object obj) :Removes one instance of obj from the invoking collection. Returns true if the element was removed. Otherwise, returns false.

15 The Methods Defined by Collection
boolean removeAII(Collection<?> c) : Removes all elements of cfrom the invoking collection. Returns true if the collection changed (i.e., elements were removed). Otherwise, returns false. boolean retainAII(Collection<?> c) : Removes all elements from the invoking collection except those in c. Returns true if the collection changed (i.e., elements were removed). Otherwise, returns false. int size( ) : Returns the number of elements held in the invoking collection. Object[ ] toArray( ) : Returns an array that contains all the elements stored in the invoking collection. The array elements are copies of the collection elements. <T> T[ ] toArray(T array\ ]) : Returns an array that contains the elements of the invoking collection. The array elements are copies of the collection elements. If the size of array equals the number of elements, these are returned in array. If the size of array is less than the number of elements, a new array of the necessary size is allocated and returned. If the size of array is greater than the number of elements, the array element following the last collection element is set to null. An ArrayStoreException is thrown if any collection element has a type that is not a subtype of array.

16 The List Interface The List interface extends Collection and declares the behavior of a collection that stores a sequence of elements. Elements can be inserted or accessed by their position in the list, using a zero-based index. A list may contain duplicate elements. List is a generic interface that has this declaration: interface List<E> Here, E specifies the type of objects that the list will hold. In addition to the methods defined by Collection, List defines some of its own.

17 The Methods Defined by List
void add(int index, E obj) : Inserts obj into the invoking list at the index passed in index. Any preexisting elements at or beyond the point of insertion are shifted up. Thus, no elements are overwritten. boolean addAII(int index, Collection<? extends E> c) : Inserts all elements of c into the invoking list at the index passed in index. Any preexisting elements at or beyond the point of insertion are shifted up. Thus, no elements are overwritten. Returns true if the invoking list changes and returns false otherwise. E get(int index) : Returns the object stored at the specified index within the invoking collection. int indexOf(Object obj) : Returns the index of the first instance of obj in the invoking list. If obj is not an element of the list, -1 is returned. int lastlndexOf(Object obj) : Returns the index of the last instance of obj in the invoking list. If obj is not an element of the list, -1 is returned. Listlterator<E> listlterator( ) : Returns an iterator to the start of the invoking list. Listlterator<E> listlterator(int index) : Returns an iterator to the invoking list that begins at the specified index. E remove(int index) : Removes the element at position index from the invoking list and returns the deleted element. The resulting list is compacted. That is, the indexes of subsequent elements are decremented by one. E set(int index, E obj) : Assigns obj to the location specified by index within the invoking list. List<E> subList(int start, int end) : Returns a list that includes elements from start to end-1 in the invoking list. Elements in the returned list are also referenced by the invoking object.

18 The Set interface The Set interface defines a set. It extends Collection and declares the behavior of a collection that does not allow duplicate elements. Therefore, the add( ) method returns false if an attempt is made to add duplicate elements to a set. It does not define any additional methods of its own. Set is a generic interface that has this declaration: interface Set<E> Here, E specifies the type of objects that the set will hold.

19 The Queue Interface The Queue interface extends Collection and declares the behavior of a queue, which is often a first-in, first-out list. However, there are types of queues in which the ordering is based upon other criteria. Queue is a generic interface that has this declaration: interface Queue<E> Here, E specifies the type of objects that the queue will hold.

20 The Methods Defined by Queue
E element( ) : Returns the element at the head of the Queue. The element is not removed. It throws NoSuchElementException if the queue is empty. boolean offer(E obj) : Attempts to add obj to the queue. Returns true if obj 'was added and false otherwise. E peek( ) : Returns the element at the head of the queue. It returns null if the queue is empty. The element is not removed. E poll( ) : Returns the element at the head of the queue, removing the element in the process. It returns null if the queue is empty. E remove( ) Removes the element at the head of the queue, returning the element in the process. It throws NoSuchElementException if the queue is empty.

21 The Collection Classes
They are the standard classes that implement the collection interface. Some of the classes provide full implementations that can be used as-is. Others are abstract, providing skeletal implementations that are used as starting points for creating concrete collections. None of the collection classes are synchronized, but it is possible to obtain synchronized versions.

22 The standard collection classes
AbstractCollection : Implements most of the Collection interface. AbstractList : Extends AbstractCollection and implements most of the List interface. AbstractQueue : Extends AbstractCollection and implements parts of the Queue interface. AbstractSequentialList : Extends AbstractList for use by a collection that uses sequential rather than random access of its elements. LinkedList : Implements a linked list by extending AbstractSequentialList. ArrayList : Implements a dynamic array by extending AbstractList.

23 The standard collection classes
ArrayDeque : Implements a dynamic double-ended queue by extending AbstractCollection and implementing the Deque interface. (Added by Java SE 6.) AbstractSet : Extends AbstractCollection and implements most of the Set interface. EnumSet : Extends AbstractSet for use with enum elements. HashSet :Extends AbstractSet for use with a hash table. LinkedHashSet : Extends HashSet to allow insertion-order iterations. PriorityQueue: Extends AbstractQueue to support a priority-based queue. TreeSet : Implements a set stored in a tree. Extends AbstractSet.

24 The ArrayList Class The ArrayList class extends AbstractList and implements the List interface. ArrayList is a generic class that has this declaration: class ArrayList<E> Here, E specifies the type of objects that the list will hold. ArrayList supports dynamic arrays that can grow as needed. In Java, standard arrays are of a fixed length. But, sometimes, you may not know until run time precisely how large an array you need. an ArrayList is a variable-length array of object references.An ArrayList can dynamically increase or decrease in size.

25 ArrayList has the constructors shown here: ArrayList( ) : builds an empty array list. Arraylist(Collection<? extends E> c) : builds an array list that is initialized with the elements of the collection c. ArrayList(int capacity) : builds an array list that is initialized with the elements of the collection c. The capacity is the size of the underlying array that is used to store the elements. The capacity grows automatically as elements are added to an array list.

26 // Demonstrate ArrayList.
import java.util.*; class ArrayListDemo { public static void main(String args [] ) { // Create an array list. The output from this program is shown here: ArrayList<String> al = new ArrayList<String> ( ) ; System. out .println (" Initial size of al : " + Initial size of al : al . size ( ) ) ; Size of al after additions: 7 // Add elements to the array list. Contents of al: [C, A2 , A, E, B, D, F] al . add ( Size of al after deletions: 5 Contents of al : [C, A2, E, B, D] al.addd, "A2") ; System. out .println ( "Size of al after additions: // Display the array list. System. out .println ( "Contents of al : " + al) ; // Remove elements from the array list, al . remove ( "F" ) ; al . remove (2 ) ; System. out .println ( "Size of al after deletions: " + System. out .println ( "Contents of al : " + al) ; }}

27 The HashSet Class HashSet extends AbstractSet and implements the Set interface. It creates a collection that uses a hash table for storage. HashSet is a generic class that has this declaration: class HashSet<E> Here, E specifies the type of objects that the set will hold. A hash table stores information by using a mechanism called hashing. In hashing, the informational content of a key is used to determine a unique value, called its hash code. The hash code is then used as the index at which the data associated with the key is stored. The transformation of the key into its hash code is performed automatically — you never see the hash code itself. Also, your code can't directly index the hash table. The advantage of hashing is that it allows the execution time of add( ), contains( ), remove( ), and size( ) to remain constant even for large sets.

28 The following constructors are defined: HashSet( ) : form constructs a default hash set. HashSet(Collection<? extends E> c) : initializes the hash set by using the elements of c. HashSet(int capacity) : initializes the capacity of the hash set to capacity. (The default capacity is 16.) HashSet(int capacity, float fillRatio) : initializes both the capacity and the fill ratio (also called load capacity) of the hash set from its arguments. The fill ratio must be between 0.0 and 1.0, and it determines how full the hash set can be before it is resized upward. Specifically, when the number of elements is greater than the capacity of the hash set multiplied by its fill ratio, the hash set is expanded. For constructors that do not take a fill ratio, 0.75 is used. HashSet does not define any additional methods beyond those provided by its superclasses and interfaces. HashSet does not guarantee the order of its elements, because the process of hashing doesn't usually lend itself to the creation of sorted sets. If you need sorted storage, then another collection, such as TreeSet, is a better choice.

29 Here is an example that demonstrates HashSet:
import j ava . util . * ; class HashSetDemo { public static void main(String args [] ) { / / Create a hash set . HashSet<String> hs = new HashSet<String> ( ) ; // Add elements hs .add ( "B" ) hs .add ( "A" ) hs .add("D") hs .add("E") hs .add("C") hs .add("F") System. out .println (hs) ; } } The following is the output from this program: [D, A, F, C, B, E] As explained, the elements are not stored in sorted order, and the precise output may vary.

30 The TreeSet Class TreeSet extends AbstractSet and implements the NavigableSet interface. It creates a collection that uses a tree for storage. Objects are stored in sorted, ascending order. Access and retrieval times are quite fast, which makes TreeSet an excellent choice when storing large amounts of sorted information that must be found quickly. TreeSet is a generic class that has this declaration: class TreeSet<E> Here, E specifies the type of objects that the set will hold.

31 TreeSet has the following constructors:
TreeSet( ) : constructs an empty tree set that will be sorted in ascending order according to the natural order of its elements. TreeSet(Collection<? extends E> c) : builds a tree set that contains the elements of c. TreeSet(Comparator<? super E> comp) : constructs an empty tree set that will be sorted according to the comparator specified by comp. TreeSet(SortedSet<E> ss) :builds a tree set that contains the elements of ss.

32 //Here is an example that demonstrates a TreeSet: import java. util
//Here is an example that demonstrates a TreeSet: import java.util.*; class TreeSetDemo { public static void main(String args [] ) { // Create a tree set. TreeSet<String> ts = new TreeSet<String> ( ) ; // Add elements to the tree set. ts.add('C" ) ; ts.add('A") ; ts.add('B") ; ts.add("E") ; ts.add('F" ) ; ts.add('D") ; System. out .println (ts) ; } } The output from this program is shown here: [A, B, C, D, E, F] As explained, because TreeSet stores its elements in a tree, they are automatically arranged in sorted order, as the output confirms.

33 Accessing a Collection via an Iterator
Often, you will want to cycle through the elements in a collection. For example, you might want to display each element. One way to do this is to employ an iterator, which is an object that implements either the Iterator or the Listlterator interface. Iterator enables you to cycle through a collection, obtaining or removing elements. Listlterator extends Iterator to allow bidirectional traversal of a list, and the modification of elements. Iterator and Listlterator are generic interfaces which are declared as shown here: interface Iterator<E> interface ListIterator<E> Here, E specifies the type of objects being iterated.

34 The Methods Defined by Iterator
boolean hasNext( ) : Returns true if there are more elements. Otherwise, returns false. E next( ) : Returns the next element. Throws NoSuchElementException if there is not a next element. void remove( ) :Removes the current element. Throw IllegalStateException if an attempt is made to call remove( ) that is not preceded by a call to next( ). In general, to use an iterator to cycle through the contents of a collection, follow these steps: 1. Obtain an iterator to the start of the collection by calling the collection's iterator( ) method. 2. Set up a loop that makes a call to hasNext( ). Have the loop iterate as long as hasNext( ) returns true. 3. Within the loop, obtain each element by calling next( ).

35 The Methods Defined by Listlterator
void add(E obj) : Inserts obj into the list in front of the element that will be returned by the next call to next( ). boolean hasNext( ) : Returns true if there is a next element. Otherwise, returns false. boolean hasPrevious( ) : Returns true if there is a previous element. Otherwise, returns false. E next( ) : Returns the next element. A NoSuchElementException is thrown if there is not a next element. int nextlndex( ) : Returns the index of the next element. If there is not a next element, returns the size of the list. E previous( ) : Returns the previous element. A NoSuchElementException is thrown if there is not a previous element. int previouslndex( ) : Returns the index of the previous element. If there is not a previous element, returns -1. void remove( ) : Removes the current element from the list. An HlegalStateException is thrown if remove( ) is called before next( ) or previous( ) is invoked. void set(E obj) : Assigns obj to the current element. This is the element last returned by a call to either next( ) or previous( ).

36 System. out .print ( "Modified contents of al : ");
// Demonstrate iterators, itr = al . iterator () ; import java.util.*; class IteratorDemo { String element = itr.nextf); public static void main(String args [] ) { System . out . print (element + " "); // Create an array list. ArrayList<String> al = new ArrayList<String> ( ) ; // Add elements to the array list. // Now, display the list backwards. al.add( “C”); System. out .print ( "Modified list backwards: "); al add( “’A” ); while ( litr . hasPrevious ) al.add( “E”); { al .add( “B”); String element = litr .previous () ; al .add( “D”); al .add( “F”); // Use iterator to display contents of al . System. out .print ( "Original contents of al : " ) ; } } Iterator<String> itr = al . iterator () ; while (itr . hasNext () ) { The output is shown here: String element = itr. next (); System . out . print (element + " " ) ; Original contents of al : C A E B D F } Modified contents of al : C+ A+ E+ B+ D+ F+ System. out .println ( ) ; Modified list backwards: F+ D+ B+ E+ A+ C+ // Modify objects being iterated. ListIterator<String> litr = al . listlterator () ; while (litr . hasNext () ) { String element = litr. next (); litr . set (element + "+");

37 The For-Each Alternative to Iterators
If you won't be modifying the contents of a collection or obtaining elements in reverse order, then the for-each version of the for loop is often a more convenient alternative to cycling through a collection than is using an iterator.

38 The Map Interfaces A map is an object that stores associations between keys and values, or key/value pairs. Given a key, you can find its value. Both keys and values are objects. The keys must be unique, but the values may be duplicated. Some maps can accept a null key and null values, others cannot. There is one key point about maps that is important to mention at the outset: they don't implement the Iterable interface. This means that you cannot cycle through a map using a for-each style for loop. Furthermore, you can't obtain an iterator to a map. However, as you will soon see, you can obtain a collection-view of a map, which does allow the use of either the for loop or an iterator.

39 The map interfaces define the character and nature of maps
The map interfaces define the character and nature of maps. The following interfaces support maps: Map : Maps unique keys to values. Map. Entry: Describes an element (a key/value pair) in a map. This is an inner class of Map. NavigableMap : Extends SortedMap to handle the retrieval of entries based on closest-match searches. (Added by Java SE 6.) SortedMap :Extends Map so that the keys are maintained in ascending order.

40 The Map Interface The Map interface maps unique keys to values. A key is an object that you use to retrieve a value at a later date. Given a key and a value, you can store the value in a Map object. After the value is stored, you can retrieve it by using its key. Map is generic and is declared as shown here: interface Map<K, V> Here, K specifies the type of keys, and V specifies the type of values.

41 The Methods Defined by Map
void clear( ) : removes all key/value pairs from the invoking map. boolean containsKey(Object k) : Returns true if the invoking map contains (tasa key. Otherwise, returns false. boolean containsValue(Object v) : Returns true if the map contains vas a value. Otherwise, returns false. Set<Map.Entry<K, V» entrySet( ) :Returns a Set that contains the entries in the map. The set contains objects of type Map. Entry. Thus, this method provides a set-view of the invoking map. boolean equals(Object obj) : Returns true if obj is a Map and contains the same entries. Otherwise, returns false. V get(Object k) : Returns the value associated with the key k. Returns null if the key is not found. int hashCode( ) : Returns the hash code for the invoking map. boolean isEmpty( ) : Returns true if the invoking map is empty. Otherwise, returns false. Set<K> keySet( ) : Returns a Set that contains the keys in the invoking map. This method provides a set-view of the keys in the invoking map. V put(K k, V v) : Puts an entry in the invoking map, overwriting any previous value associated with the key. The key and value are k and v r respectively. Returns null if the key did not already exist. Otherwise, the previous value linked to the key is returned. void putAII(Map<? extends K, ? extends V> m) Puts all the entries from m into this map. V remove(Object k) : Removes the entry whose key equals k. int size( ): Returns the number of key/value pairs in the map. Collection<V> values( ) :Returns a collection containing the values in the map. This method provides a collection-view of the values in the map.

42 The SortedMap Interface
The SortedMap interface extends Map. It ensures that the entries are maintained in ascending order based on the keys. SortedMap is generic and is declared as shown here: interface SortedMap <K, V> Here, K specifies the type of keys, and V specifies the type of values.

43 The Methods Defined by SortedMap
Comparator(? super K> comparator ) : Returns the invoking sorted map's comparator. If natural ordering is used for the invoking map, null is returned. K firstKey( ) : Returns the first key in the invoking map. SortedMap<K,V:>headMap(K end): Returns a sorted map for those map entries with keys that are less than end. K lastKey( ) : Returns the last key in the invoking map. SortedMap<K, V> subMap(K start, K end): Returns a map containing those entries with keys that are greater than or equal to start and less than end. SortedMap<K, V> tailMap(K start): Returns a map containing those entries with keys that are greater than or equal to start.

44 The NavigableMap Interface
The NavigableMap interface was added by Java SE 6. It extends SortedMap and declares the behavior of a map that supports the retrieval of entries based on the closest match to a given key or keys. NavigableMap is a generic interface that has this declaration: interface NavigableMap<K,V> Here, K specifies the type of the keys, and V specifies the type of the values associated with the keys.

45 Some Methods defined by NavigableMap
Map.Entry<K,V> ceilingEntry(K obj) : Searches the map for the smallest key k such that k >= obj. If such a key is found, its entry is returned. Otherwise, null is returned. K ceilingKey(K obj) :Searches the map for the smallest key k such that k >= obj. If such a key is found, it is returned. Otherwise, null is returned. NavigableSet<K> descendingKeySet( ) :Returns a NavigableSet that contains the keys in the invoking map in reverse order. Thus, it returns a reverse set-view of the keys. The resulting set is backed by the map. NavigableMap<K,V> descendingMap( ) :Returns a NavigableMap that is the reverse of the invoking map. The resulting map is backed by the invoking map. Map.Entry<K,V> firstEntry( ) :Returns the first entry in the map. This is the entry with the least key.

46 The Map. Entry Interface
The Map. Entry interface enables you to work with a map entry. Recall that the entrySet( ) method declared by the Map interface returns a Set containing the map entries. Each of these set elements is a Map. Entry object. Map. Entry is generic and is declared like this: interface Map.Entry<K, V> Here, K specifies the type of keys, and V specifies the type of values.

47 The Methods Defined by Map.Entry
boolean equals(Object obj) : Returns true if obj is a Map.Entry whose key and value are equal to that of the invoking object. K getKey( ) : Returns the key for this map entry. V getValue( ) : Returns the value for this map entry. int hashCode( ) : Returns the hash code for this map entry. V setValue(V v) : Sets the value for this map entry to v. A ClassCastException is thrown if v is not the correct type for the map. An MlegalArgumentException is thrown if there is a problem with v. A NullPointerException is thrown if v is null and the map does not permit null keys. An UnsupportedOperationException is thrown if the map cannot be changed.

48 The Map Classes Several classes provide implementations of the map interfaces. The classes that can be used for maps are summarized here: AbstractMap : Implements most of the Map interface. EnumMap : Extends AbstractMap for use with enum keys. HashMap : Extends AbstractMap to use a hash table. TreeMap :Extends AbstractMap to use a tree. WeakHashMap : Extends AbstractMap to use a hash table with weak keys. LinkedHashMap : Extends HashMap to allow insertion-order iterations. IdentityHashMap : Extends AbstractMap and uses reference equality when comparing documents.

49 AbstractMap is a superclass for all concrete map implementations.
WeakHashMap implements a map that uses "weak keys," which allows an element in a map to be garbage-collected when its key is otherwise unused.

50 The HashMap Class The HashMap class extends AbstractMap and implements the Map interface. It uses a hash table to store the map. This allows the execution time of get( ) and put( ) to remain constant even for large sets. HashMap is a generic class that has this declaration: class HashMap<K, V> Here, K specifies the type of keys, and V specifies the type of values.

51 The following constructors are defined:
HashMap( ) : constructs a default hash map HashMap(Map<? extends K, ? extends V> m) : initializes the hash map by using the elements of m. HashMap(int capacity): initializes the capacity of the hash map to capacity. HashMap(int capacity, float fillRatio) : initializes both the capacity and fill ratio of the hash map by using its arguments. The meaning of capacity and fill ratio is the same as for HashSet, described earlier. The default capacity is 16. The default fill ratio is 0.75.

52 //The following program illustrates HashMap
//The following program illustrates HashMap. It maps names to account balances. import java.util.*; class HashMapDemo { public static void main (String args [] ) { // Create a hash map. HashMap<String, Double> hm = new HashMap<String, Double>(); // Put elements to the map hm . put (" John Doe", new Double ( ) ) ; hm.put(“Tom Smith", new Double ( )) ; hm . put ( “11 Jane Baker", new Double ( ) ) ; hm . put ( " Tod Hall", new Double ( )) ; hm. put ( "Ralph Smith", new Double ( ) ) ; // Get a set of the entries. Set<Map . Entry<String, Double>> set = hm . entrySet ( ) ; // Display the set. for (Map . Entry<String, Double> me : set) { System . out . print (me . getKey ( ) + ": "); System . out . println (me . getValue ( ) ) ; } System. out .println ( ) ; // Deposit 1000 into John Doe's account, double balance = hm.get("John Doe"); hm.putC'John Doe", balance ); System. out .println ( "John Doe's new balance: " + hm . get ( " John Doe " ) ) ; } } Output from this program is shown here (the precise order may vary): Ralph Smith: Tom Smith: John Doe : Tod Hall : Jane Baker: John Doe's new balance:

53 The program begins by creating a hash map and then adds the mapping of names to balances.
Next, the contents of the map are displayed by using a set-view, obtained by calling entrySet( ). The keys and values are displayed by calling the getKey( ) and getValue( ) methods that are defined by Map.Entry. Pay close attention to how the deposit is made into John Doe's account. The put( ) method automatically replaces any pre existing value that is associated with the specified key with the new value. Thus, after John Doe's account is updated, the hash map will still contain just one "John Doe" account.

54 The TreeMap Class The TreeMap class extends AbstractMap and implements the NavigableMap interface. It creates maps stored in a tree structure. Unlike a hash map, a tree map guarantees that its elements will be sorted in ascending key order. TreeMap is a generic class that has this declaration: class TreeMap<K, V> Here, K specifies the type of keys, and V specifies the type of values.

55 The following TreeMap constructors are defined:
TreeMap( ) : constructs an empty tree map that will be sorted by using the natural order of its keys TreeMap(Comparator<? super K> comp) : constructs an empty tree-based map that will be sorted by using the Comparator comp. TreeMap(Map<? extends K, ? extends V> m) : initializes a tree map with the entries from m, which will be sorted by using the natural order of the keys. TreeMap(SortedMap<K, ? extends V> sm) initializes a tree map with the entries from sm, which will be sorted in the same order as sm.

56 Swing Swing is a set of classes that provides more powerful and flexible GUI components than does the AWT (Abstract Window Toolkit). Simply put, Swing provides the look and feel of the modern Java GUI.

57 The origins of Swing The AWT defines a basic set of controls, windows, and dialog boxes that support a usable, but limited graphical interface. One reason for the limited nature of the AWT is that it translates its various visual components into their corresponding, platform-specific equivalents, or peers. This means that the look and feel of a component is defined by the platform, not by Java. Because the AWT components use native code resources, they are referred to as heavyweight. The use of native peers led to several problems. First, because of variations between operating systems, a component might look, or even act, differently on different platforms. This potential variability threatened the overarching philosophy of Java: write once, run anywhere. Second, the look and feel of each component was fixed (because it is defined by the platform) and could not be (easily) changed. Third, the use of heavyweight components caused some frustrating restrictions. Not long after Java's original release, it became apparent that the limitations and restrictions present in the AWT were sufficiently serious that a better approach was needed. The solution was Swing. Introduced in 1997, Swing was included as part of the Java Foundation Classes (JFC). Swing was initially available for use with Java 1.1 as a separate library. However, beginning with Java 1.2, Swing (and the rest of the JFC) was fully integrated into Java.

58 Two Key Swing Features Swing Components Are Lightweight: This means that they are written entirely in Java and do not map directly to platform-specific peers. They can be transparent, which enables nonrectangular shapes and are more efficient and more flexible. Furthermore, they do not translate into native peers and hence the look and feel of each component is determined by Swing, not by the underlying operating system. Swing supports a pluggable look and feel (PLAF). :The look and feel of a component is under the control of Swing. This fact means that it is possible to separate the look and feel of a component from the logic of the component. Separating out the look and feel provides a significant advantage: it is possible to "plug in" a new look and feel for any given component without creating any side effects in the code that uses that component. It is possible to define a look and feel that is consistent across all platforms. Conversely, it is possible to create a look and feel that acts like a specific platform.

59 Java SE 6 provides look-and-feels, such as metal and Motif
Java SE 6 provides look-and-feels, such as metal and Motif. The metal look and feel is also called the Java look and feel or default look and feel .Here we’ll use the default Java look and feel (metal) because it is platform independent.

60 The MVC Connection In general, a visual component is a composite of three distinct aspects: The way that the component looks when rendered on the screen • The way that the component reacts to the user • The state information associated with the component No matter what architecture is used to implement a component, it must implicitly contain these three parts. Over the years, one component architecture (Model-View-Controller, or MVC) has proven itself to be exceptionally effective. The MVC architecture is successful because each piece of the design corresponds to an aspect of a component. In MVC terminology, the model corresponds to the state information associated with the component.

61 Swing uses a modified version of MVC that combines the view and the controller into a single logical entity called the UI delegate. For this reason, Swing's approach is called either the Model-Delegate architecture or the Separable Model architecture. To support the Model-Delegate architecture, most Swing components contain two objects. The first represents the model. The second represents the UI delegate. Models are defined by interfaces. For example, the model for a button is defined by the ButtonModel interface. UI delegates are classes that inherit ComponentUI. For example, the UI delegate for a button is ButtonUI.

62 Components and Containers
A Swing GUI consists of two key items: components and containers. The difference between two is- A component is an independent visual control, such as a push button or slider. A container holds a group of components. Thus, a container is a special type of component that is designed to hold other components. Furthermore, in order for a component to be displayed, it must be held within a container. Thus, all Swing GUIs will have at least one container. Because containers are components, a container can also hold other containers. This enables Swing to define what is called a containment hierarchy, at the top of which must be a top-level container.

63 Components In general, Swing components are derived from the JComponent class. JComponent provides the functionality that is common to all components. For example, JComponent supports the pluggable look and feel. JComponent inherits the AWT classes Container and Component. All of Swing's components are represented by classes defined within the package javax.swing.

64 The class names for Swing components (including those used as containers).
JApplet J Frame JProgressBar JTextArea J Button JlnternalFrame JRadioButton JTextField JCheckBox J Label JRadioButtonMenultem JTextPane JCheckBoxMenultem JLayeredPane JRootPane JTogglebutton JColorChooser J Li st JScrollBar JToolBar JComboBox JMenu JScrollPane JToolTip JComponent JMenuBar JSeparator JTree JDesktopPane JMenultem JSIider JViewport JDialog JOptionPane JSpinner JWindow JEditorPane JPanel JSplitPane JFileChooser JPasswordField JTabbedPane JFormattedText Field JPopupMenu JTable

65 Containers Swing defines two types of containers. The first are top-level containers: JFrame, JApplet, JWindow, and JDialog. These containers do not inherit JComponent. They do, however, inherit the AWT classes Component and Container. Unlike Swing's other components, which are lightweight, the top-level containers are heavyweight. This makes the top-level containers a special case in the Swing component library. A top-level container is not contained within any other container. Furthermore, every containment hierarchy must begin with a top-level container. The one most commonly used for applications is JFrame. The one used for applets is JApplet. The second type of containers supported by Swing are lightweight containers. Lightweight containers do inherit JComponent. An example of a lightweight container is JPanel, which Is a general-purpose container. a lightweight container can be contained within another container. Lightweight containers are often used to organize and manage groups of related components. Thus, you can use lightweight containers such as JPanel to create subgroups of related controls that are contained within an outer container.

66 Top-Level Container Panes
Each top-level container defines a set of panes. At the top of the hierarchy is an instance of JRootPane. JRootPane is a lightweight container whose purpose is to manage the other panes. It also helps manage the optional menu bar. The panes that comprise the root pane are called the glass pane, the content pane, and the layered pane. The glass pane is the top-level pane. It sits above and completely covers all other panes. By default, it is a transparent instance of JPanel. The glass pane enables you to manage mouse events that affect the entire container (rather than an individual control) or to paint over any other component, for example. In most cases, you won't need to use the glass pane directly, but it is there if you need it. The layered pane is an instance of JLayeredPane. The layered pane allows components to be given a depth value. This value determines which component overlays another. (Thus, the layered pane lets you specify a Z-order for a component, although this is not something that you will usually need to do.) The layered pane holds the content pane and the (optional) menu bar. Although the glass pane and the layered panes are integral to the operation of a top-level container and serve important purposes, much of what they provide occurs behind the scene. The pane with which your application will interact the most is the content pane, because this is the pane to which you will add visual components. In other words, when you add a component, such as a button, to a top-level container, you will add it to the content pane. By default, the content pane is an opaque instance of JPanel.

67 There are two types of Java programs in which Swing is typically used
There are two types of Java programs in which Swing is typically used. The first is a desktop application. The second is the applet. //A simple Swing application. import j avax . swing . * ; class SwingDemo { SwingDemo ( ) { Swing programs are compiled and run in the same way as other Java applications. Thus, // Create a new JFrame container. JFrame jfrm = new JFrame ("A Simple Swing Application"); to compile this program, you can use this command line: // Give the frame an initial size, j frm. setSize (275 , 100); javac SwingDemo . j ava // Terminate the program when the user closes the application, j frm. setDef aultCloseOperation (JFrame . EXIT_ON_CLOSE) ; To run the program, use this command line: // Create a text-based label. JLabel jlab = new JLabel(" Swing means powerful GUIs."); j ava SwingDemo // Add the label to the content pane, j f rm . add ( j lab) ; When the program is run, it will produce the window shown in Figure 29-1. // Display the frame, j frm. setvisible (true) ; } public static void main(String args [] ) { // Create the frame on the event dispatching thread. SwingUtilities . invokeLater ( new Runnable() { public void run ( ) { new SwingDemo ( ) ; } } ); } }

68 The program begins by importing javax
The program begins by importing javax.swing, this package contains classes that implement labels, buttons, text controls, and menus. It will be included in all programs that use Swing. Next, the program declares the SwingDemo class and a constructor for that class. The constructor begins by creating a JFrame: JFrame jfrm = new JFrame ( "A Simple Swing Application"); This creates a container called jfrm that defines a rectangular window complete with a title bar; close, minimize, maximize, and restore buttons; and a system menu. Thus, it creates a standard, top-level window. The title of the window is passed to the constructor. The window is sized using this statement: jfrm. setSize (275 , 100); The setSize( ) method sets the dimensions of the window, which are specified in pixels. Its general form is shown here: void setSize(int width, int height) jfrm. setDefaultCloseOperation (JFrame . EXIT_ON_CLOSE) ; After this call executes, closing the window causes the entire application to terminate. The general form of setDefaultCloseOperation( ) is shown here: void setDefaultCloseOperation(int whathappens when the window is closed) The next line of code creates a Swing JLabel component: JLabel jlab = new JLabel (" Swing means powerful GUIs."); JLabel is the simplest and easiest-to-use component because it does not accept user input. It simply displays information, which can consist of text, an icon, or a combination of the two.

69 The next line of code adds the label to the content pane of the frame:
jfrm. add ( j lab) ; To add a component to a frame, you must add it to the frame's content pane. This is accomplished by calling add( ) on the JFrame reference (jfrm in this case). The general form of add( ) is shown here: Component add(Component comp) The last statement in the SwingDemo constructor causes the window to become visible: jfrm . setvisible (true) ; The setVisible( ) method is inherited from the AWT Component class. If its argument is true, the window will be displayed. Otherwise, it will be hidden. By default, a JFrame is invisible, so setVisible(true) must be called to show it. Inside main( ), a SwingDemo object is created, which causes the window and the label to be displayed. Notice that the SwingDemo constructor is invoked using these lines of code: SwingUtilities . invokeLater (new Runnable ( ) { public void run ( ) { new SwingDemo ( ) ; } }); This sequence causes a SwingDemo object to be created on the event dispatching thread rather than on the main thread of the application. Because Swing programs are event-driven and an event is passed to the application by calling an event handler defined by the application. However, the handler is executed on the event dispatching thread provided by Swing and not on the main thread of the application. To avoid problems (including the potential for deadlock), all Swing GUI components must be created and updated from the event dispatching thread, not the main thread of the application.

70 Event Handling Because JLabel does not take input from the user, it does not generate events, so no event handling was needed. However, the other Swing components do respond to user input and the events generated by those interactions need to be handled. Events can also be generated in ways not directly related to user input. For example, an event is generated when a timer goes off. The event handling mechanism used by Swing is the same as that used by the AWT and is called the delegation event model. In many cases, Swing uses the same events as does the AWT, and these events are packaged in java.awt.event. Events specific to Swing are stored in javax.swing.event.

71 jbtnBeta . addActionListener (new ActionListener ( ) {
// Handle an event in a Swing program. import j ava . awt . * ; j lab . setText ( "Beta was pressed."); } }); import j ava . awt . event . * ; // Add the buttons to the content pane, import j avax . swing . * ; j frm . add (jbtnAlpha) ; class EventDemo { j frm . add (jbtnBeta) ; JLabel jlab; // Create a text-based label. EventDemo ( ) { jlab = new JLabel (" Press a button.") ; // Create a new JFrame container. // Add the label to the content pane, JFrame jfrm = new JFrame ( "An Event Example"); j frm . add ( j lab) ; // Specify FlowLayout for the layout manager, // Display the frame. j frm. setLayout (new FlowLayout ( ) ) ; j f rm. setvisible (true) ; } // Give the frame an initial size, public static void main (String args [] ) { j frm. setSize (220 , 90); // Create the frame on the event dispatching thread. // Terminate the program when the user closes the application, SwingUtilities . invokeLater (new Runnable ( ) { public void run ( ) { j frm. setDef aultCloseOperation (JFrame . EXIT_ON_CLOSE) ; new EventDemo ( ) ; } }); } } // Make two buttons. JButton jbtnAlpha = new JButton ( "Alpha" ) ; JButton jbtnBeta = new JButton ( "Beta" ) ; // Add action listener for Alpha. jbtnAlpha . addActionListener (new ActionListener ( ) { public void actionPerf ormed (ActionEvent ae) { jlab . setText ( "Alpha was pressed."); } }); // Add action listener for Beta.

72 The program now imports both the java. awt and java. awt
The program now imports both the java.awt and java.awt.event packages. The java.awt package is needed because it contains the FlowLayout class, which supports the standard flow layout manager used to lay out components in a frame.The java.awt.event package is needed because it defines the ActionListener interface and the ActionEvent class. The EventDemo constructor begins by creating a JFrame called jfrm. It then sets the layout manager for the content pane of jfrm to FlowLayout. using this statement: j f rm. setLayout (new FlowLayout ( ) ) ; EventDemo( ) creates two push buttons, as shown here: JButton jbtnAlpha = new JButton ( "Alpha" ) ; JButton jbtnBeta = new JButton ( "Beta" ) ; JButton supplies several constructors. The one used here is JButton(String msg) The msg parameter specifies the string that will be displayed inside the button. When a push button is pressed, it generates an ActionEvent. Thus, JButton provides the addActionListener( ) method, the ActionListener interface defines only one method: actionPerformed().The general form of it is: void actionPerformed(ActionEvent ae) This method is called when a button is pressed. In other words, it is the event handler that is called when a button press event has occurred.

73 Next, the buttons are added to the content pane of jfrm:
j frm . add (jbtnAlpha) ; j frm. add (jbtnBeta) ; Finally, jlab is added to the content pane and window is made visible. When you run the program, each time you press a button, a message is displayed in the label that indicates which button was pressed. One last point: Remember that all event handlers, such as actionPerformed( ), are called on the event dispatching thread.

74 The Swing components The Swing components provide rich functionality and allow a high level of customization. The Swing component classes described in this chapter are shown here: These components are all lightweight, which means that they are all derived from JComponent. J Button JCheckBox JComboBox JLabel J Li st JRadioButton JScrollPane JTabbedPane JTable JTextField JToggleButton JTree

75 JLabel JLabel is Swing's easiest-to-use component. JLabel can be used to display text and /or an icon. It is a passive component in that it does not respond to user input. JLabel defines several constructors. Here are three of them: JLabel(Icon icon) JLabel(String str) JLabel(String str, Icon icon, int align) Here, str and icon are the text and icon used for the label. The align argument specifies the horizontal alignment of the text and / or icon within the dimensions of the label. It must be one of the following values: LEFT, RIGHT, CENTER, LEADING, or TRAILING. Icons are specified by objects of type Icon, which is an interface defined by Swing. The easiest way to obtain an icon is to use the Imagelcon class. Imagelcon implements Icon and encapsulates an image. Thus, an object of type Imagelcon can be passed as an argument to the Icon parameter of JLabel's constructor.

76 demonstrate JLabel and Imagelcon.
import j ava . awt . * ; /* <applet code=" JLabelDemo" width=250 height=150> </applet> */ public class JLabelDemo extends JApplet { public void initO { try { SwingUtilities . invokeAndWait ( new Runnable() { public void run ( ) { makeGUI ( ) ; } ) ; } catch (Exception exc) { System . out . println ( "Can ' t create because of " + exc); private void raakeGUI ( ) { // Create an icon. Imagelcon ii = new Imagelcon (" f ranee . gif ") ; // Create a label. JLabel jl = new JLabel ( "France" , ii, JLabel . CENTER) ; // Add the label to the content pane, add ( j 1 ) ;


Download ppt "Generics And Collection Interface"

Similar presentations


Ads by Google