Core Collections) Intervw Questns

download Core Collections) Intervw Questns

of 72

Transcript of Core Collections) Intervw Questns

  • 8/2/2019 Core Collections) Intervw Questns

    1/72

    Introduction to the Collections Framework

    This module takes you on an extended tour of the Collections Framework, firsintroduced with the Java 2 platform, Standard Edition, version 1.2. TheCollections Framework provides a well-designed set of interfaces and classesfor storing and manipulating groups of data as a single unit, a collection. Theframework provides a convenient API to many of the abstract data types

    familiar from computer science data structure curriculum: maps, sets, lists,trees, arrays, hashtables and other collections. Because of their object-oriented design, the Java classes in the Collections Framework encapsulateboth the data structures and the algorithms associated with theseabstractions. The framework provides a standard programming interface tomany of the most common abstractions, without burdening the programmerwith too many procedures and interfaces. The operations supported by thecollections framework nevertheless permit the programmer to easily definehigher level data abstractions, such as stacks, queues, and thread-safe

    collections.

    One thing worth noting early on is that while the framework is included withthe Java 2 platform, a subset form is available for use with Java 1.1 runtimeenvironments. The framework subset is discussed in a later section.

    Before diving into the Collections Framework, it helps to understand some ofthe terminology and set theory involved when working with the framework.

    Mathematical BackgroundIn common usage a collection is the same as the intuitive, mathamaticalconcept of a set. A set is just a group of unique items, meaning that the groucontains no duplicates. The Collections Framework in fact includes a Setinterface, and a number of concrete Set classes. But the formal notion of a sepredates Java technology by a century, when the British mathematicianGeorge Boole defined it in formal logic. Most people learned some set theoryin elementary school when introduced to "set intersection" and "set union"through the familiar Venn Diagrams:

    http://java.sun.com/developer/onlineTraining/collections/Collection.html#JDK11Supporthttp://java.sun.com/developer/onlineTraining/collections/Collection.html#JDK11Support
  • 8/2/2019 Core Collections) Intervw Questns

    2/72

    Some real-world examples of sets include the following:

    The set of uppercase letters 'A' through 'Z'

    The set of nonnegative integers {0, 1, 2 ...}

    The set of reserved Java programming language keywords {'import', 'class','public', 'protected'...}

    A set of people (friends, employees, clients, ...)

    The set of records returned by a database query

    The set ofComponent objects in a Container

    The set of all pairs

    The empty set {}

    These examples show the basic properties of sets:

    Sets contains only one instance of each item

    Sets may be finite or infinite

    Sets can define abstract concepts

    Sets are fundamental to logic, mathematics, and computer science, but alsopractical in everyday applications in business and systems. The idea of a"connection pool" is a set of open connections to a database server. Webservers have to manage sets of clients and connections. File descriptorsprovide another example of a set in the operating system.

  • 8/2/2019 Core Collections) Intervw Questns

    3/72

    A map is a special kind of set. It is a set of pairs, each pair representing aone-directional "mapping" from one element to another. Some examples ofmaps are:

    The map of IP addresses to domain names (DNS)

    A map from keys to database records

    A dictionary (words mapped to meanings)

    The conversion from base 2 to base 10

    Like sets, the idea behind a map is much older than the Java programminglanguage, older even than computer science. Sets and maps are importanttools in mathematics and their properties are well-understood. People alsolong recognized the usefulness of solving programming problems with sets

    and maps. A language called SETL (Set Language) invented in 1969 includedsets as one of its only primitive data types (SETL also included garbagecollection--not widely accepted until Java technology developed in the 1990'sAlthough sets and maps appear in many languages including C++, theCollections Framework is perhaps the best designed set and map package yetwritten for a popular language. Users of C++ Standard Template Library (STLand Smalltalk's collection hierarchy might argue that last point.

    Also because they are sets, maps can be finite or infinite. An example of an

    infinite map is the conversion from base 2 to base 10. Unfortunately, theCollections Framework does not support infatuate maps--sometimes amathematical function, formula or algorithm is preferred. But when a problemcan be solved with a finite map, the Collections Framework provides the Javaprogrammer with a useful API.

    Because the Collections Framework has formal definitions for the classes Set,Collection, and Map, you'll notice the lower case words set, collection and mato distinguish the implementation from the concept.

    Collection Interfaces and Classes

    Now that you have some set theory under your belt, you should be able tounderstand with the Collections Framework more easily. The CollectionsFramework is made up of a set of interfaces for working with groups ofobjects. The different interfaces describe the different types of groups. For thmost part, once you understand the interfaces, you understand theframework. While you always need to create specific implementations of theinterfaces, access to the actual collection should be restricted to the use of th

  • 8/2/2019 Core Collections) Intervw Questns

    4/72

    interface methods, thus allowing you to change the underlying data structurewithout altering the rest of your code. The following diagrams shows theframework interface hierarchy.

    One might think that Map would extend Collection. In mathematics, a map is

    just a collection of pairs. In the Collections Framework, however, theinterfaces Map and Collection are distinct with no lineage in the hierarchy. Threasons for this distinction have to do with the waysthat Set and Map areused in the Java technology libraries. The typical application of a Map is toprovide access to values stored by keys. The set of collection operations areall there, but you work with a key-value pair, instead of an isolated element.Map is therefore designed to support the basic operations ofget() and put()which are not required by Set. Moreover, there are methods that return Setviews ofMap objects:

    Set set = aMap.keySet();

    When designing software with the Collections Framework, it is useful toremember the following hierarchical relationships of the four basic interfacesof the framework:

    The Collection interface is a group of objects, with duplicates allowed

    Set extends Collection but forbids duplicates

    List extends Collection also, allows duplicates and introduces positionalindexing

    Map extends neither Set nor Collection

    Moving on to the framework implementations, the concrete collection classesfollow a naming convention, combining the underlying data structure with theframework interface. The following table shows the six collectionimplementations introduced with the Java 2 framework, in addition to the fou

    http://java.sun.com/products/jdk/1.2/docs/api/java/util/Map.html#get(java.lang.Object)http://java.sun.com/products/jdk/1.2/docs/api/java/util/Map.html#put(java.lang.Object,%20java.lang.Object)http://java.sun.com/products/jdk/1.2/docs/api/java/util/Map.html#get(java.lang.Object)http://java.sun.com/products/jdk/1.2/docs/api/java/util/Map.html#put(java.lang.Object,%20java.lang.Object)
  • 8/2/2019 Core Collections) Intervw Questns

    5/72

    historical collection classes. For information on how the historical collectionclasses changed, like how Hashtable was reworked into the framework, seethe Historical Collection Classes section, below.

    Interface Implementation Historical

    Set HashSet TreeSet

    List ArrayList LinkedList VectorStack

    Map HashMap TreeMap HashtableProperties

    There are no implementations of the Collection interface. The historicalcollection classes are called such because they have been around since the 1release of the Java class libraries.

    If you are moving from the historical collection classes to the new frameworkclasses, one of the primary differences is that all operations areunsynchronized with the new classes. While you can add synchronization tothe new classes, you cannot remove it from the old.

    Collection Interface

    The Collection interface is used to represent any group of objects, orelements. You use the interface when you wish to work with a group ofelements in as general a manner as possible. Here is a list of the public

    methods ofCollection in Unified Modeling Language (UML) notation.

    The interface supports basic operations like adding and removing. When youtry to remove an element, only a single instance of the element in thecollection is removed, if present.

    http://java.sun.com/developer/onlineTraining/collections/Collection.html#HistoricalCollectionClasseshttp://java.sun.com/developer/onlineTraining/collections/Collection.html#HistoricalCollectionClasses
  • 8/2/2019 Core Collections) Intervw Questns

    6/72

    boolean add(Object element)

    boolean remove(Object element)

    The Collection interface also supports query operations:

    int size()

    boolean isEmpty()

    boolean contains(Object element)

    Iterator iterator()

    Iterator Interface

    The iterator() method of the Collection interface returns an Iterator. AnIterator is similar to the Enumeration interface, which you may already befamiliar with, and will be described later. With the Iterator interface methods,you can traverse a collection from start to finish and safely remove elementsfrom the underlying Collection:

    The remove() method is optionally supported by the underlying collection.When called, and supported, the element returned by the last next() call isremoved. To demonstrate, the following shows the use of the Iteratorinterface for a general Collection:

    Collection collection = ...;Iterator iterator = collection.iterator();while (iterator.hasNext()) {

    Object element = iterator.next();if (removalCheck(element)) {iterator.remove();

    }}

    Group Operations

    http://java.sun.com/products/jdk/1.2/docs/api/java/util/Collection.html#iterator()http://java.sun.com/developer/onlineTraining/collections/Collection.html#Enumerationhttp://java.sun.com/products/jdk/1.2/docs/api/java/util/Iterator.html#remove()http://java.sun.com/products/jdk/1.2/docs/api/java/util/Iterator.html#next()http://java.sun.com/products/jdk/1.2/docs/api/java/util/Collection.html#iterator()http://java.sun.com/developer/onlineTraining/collections/Collection.html#Enumerationhttp://java.sun.com/products/jdk/1.2/docs/api/java/util/Iterator.html#remove()http://java.sun.com/products/jdk/1.2/docs/api/java/util/Iterator.html#next()
  • 8/2/2019 Core Collections) Intervw Questns

    7/72

    Other operations the Collection interface supports are tasks done on groups oelements or the entire collection at once:

    boolean containsAll(Collection collection)

    boolean addAll(Collection collection)

    void clear()

    void removeAll(Collection collection)

    void retainAll(Collection collection)

    The containsAll() method allows you to discover if the current collectioncontains all the elements of another collection, a subset. The remainingmethods are optional, in that a specific collection might not support thealtering of the collection. The addAll() method ensures all elements fromanother collection are added to the current collection, usually a union. Theclear() method removes all elements from the current collection. TheremoveAll() method is like clear() but only removes a subset of elements. ThretainAll() method is similar to the removeAll() method, but does what mightbe perceived as the opposite. It removes from the current collection thoseelements not in the other collection, an intersection.

    The remaining two interface methods, which convert a Collection to an array,will be discussed later.

    AbstractCollection Class

    The AbstractCollection class provides the basis for the concrete collectionframework classes. While you are free to implement all the methods of theCollection interface yourself, the AbstractCollection class providesimplementations for all the methods, except for the iterator() and size()methods, which are implemented in the appropriate subclass. Optionalmethods like add() will throw an exception if the subclass doesn't override thbehavior.

    Collection Framework Design Concerns

    In the creation of the Collections Framework, the Sun development teamneeded to provide flexible interfaces that manipulated groups of elements. Tokeep the design simple, instead of providing separate interfaces for optionalcapabilities, the interfaces define all the methods an implementation classmay provide. However, some of the interface methods are optional. Becausean interface implementation must provide implementations for all the interfac

    http://java.sun.com/products/jdk/1.2/docs/api/java/util/Collection.html#containsAll(java.util.Collection)http://java.sun.com/products/jdk/1.2/docs/api/java/util/Collection.html#addAll(java.util.Collection)http://java.sun.com/products/jdk/1.2/docs/api/java/util/Collection.html#clear()http://java.sun.com/products/jdk/1.2/docs/api/java/util/Collection.html#removeAll(java.util.Collection)http://java.sun.com/products/jdk/1.2/docs/api/java/util/Collection.html#clear()http://java.sun.com/products/jdk/1.2/docs/api/java/util/Collection.html#retainAll(java.util.Collection)http://java.sun.com/products/jdk/1.2/docs/api/java/util/Collection.html#removeAll(java.util.Collection)http://java.sun.com/developer/onlineTraining/collections/Collection.html#ConvertingFromNewCollectionsToHistoricalCollectionshttp://java.sun.com/products/jdk/1.2/docs/api/java/util/AbstractCollection.html#add(java.lang.Object)http://java.sun.com/products/jdk/1.2/docs/api/java/util/Collection.html#containsAll(java.util.Collection)http://java.sun.com/products/jdk/1.2/docs/api/java/util/Collection.html#addAll(java.util.Collection)http://java.sun.com/products/jdk/1.2/docs/api/java/util/Collection.html#clear()http://java.sun.com/products/jdk/1.2/docs/api/java/util/Collection.html#removeAll(java.util.Collection)http://java.sun.com/products/jdk/1.2/docs/api/java/util/Collection.html#clear()http://java.sun.com/products/jdk/1.2/docs/api/java/util/Collection.html#retainAll(java.util.Collection)http://java.sun.com/products/jdk/1.2/docs/api/java/util/Collection.html#removeAll(java.util.Collection)http://java.sun.com/developer/onlineTraining/collections/Collection.html#ConvertingFromNewCollectionsToHistoricalCollectionshttp://java.sun.com/products/jdk/1.2/docs/api/java/util/AbstractCollection.html#add(java.lang.Object)
  • 8/2/2019 Core Collections) Intervw Questns

    8/72

    methods, there needed to be a way for a caller to know if an optional methodis not supported. The manner the framework development team chose tosignal callers when an optional method is called was to thrown anUnsupportedOperationException . If in the course of using a collection, anUnsupportedOperationException is thrown, like trying to add to a read-onlycollection, then the operation failed because it is not supported. To avoidhaving to place all collection operations within a try-catch block, theUnsupportedOperationException class is an extension of the RuntimeExceptioclass.

    In addition to handling optional operations with a runtime exception, theiterators for the concrete collection implementations are fail-fast. That meansthat if you are using an Iterator to traverse a collection while underlyingcollection is being modified by another thread, then the Iterator failsimmediately by throwing a ConcurrentModificationException (anotherRuntimeException). That means the next time an Iterator method is called,and the underlying collection has been modified, theConcurrentModificationException exception gets thrown.

    Set Interface

    The Set interface extends the Collection interface and, by definition, forbidsduplicates within the collection. All the original methods are present and nonew methods are introduced. The concrete Set implementation classes rely othe equals() method of the object added to check for equality.

    HashSet, TreeSet Classes

    The Collections Framework provides two general-purpose implementations ofthe Set interface: HashSet and TreeSet. More often than not, you will use aHashSet for storing your duplicate-free collection. For efficiency, objects addeto a HashSet need to implement the hashCode() method in a manner that

    http://java.sun.com/products/jdk/1.2/docs/api/java/util/Set.html#equals(java.lang.Object)http://java.sun.com/products/jdk/1.2/docs/api/java/util/Set.html#equals(java.lang.Object)
  • 8/2/2019 Core Collections) Intervw Questns

    9/72

    properly distributes the hash codes. While most system classes override thedefault hashCode() implementation in Object, when creating your own classeto add to a HashSet remember to override hashCode(). The TreeSetimplementation is useful when you need to extract elements from a collectionin a sorted manner. In order to work property, elements added to a TreeSetmust be sortable. The Collections Framework adds support for Comparableelements and will be covered in detail later. For now, just assume a treeknows how to keep elements of thejava.lang wrapper classes sorted. It isgenerally faster to add elements to a HashSet, then convert the collection to TreeSet for sorted traversal.

    To optimize HashSet space usage, you can tune the initial capacity and loadfactor. The TreeSet has no tuning options, as the tree is always balanced,ensuring log(n) performance for insertions, deletions, and queries.

    Both HashSet and TreeSet implement the Cloneable interface.

    Set Usage Example

    To demonstrate the use of the concrete Set classes, the following programcreates a HashSet and adds a group of names, including one name twice. Theprogram than prints out the list of names in the set, demonstrating theduplicate name isn't present. Next, the program treats the set as a TreeSetand displays the list sorted.

    import java.util.*;

    public class SetExample {public static void main(String args[]) {Set set = new HashSet();set.add("Bernadine");set.add("Elizabeth");set.add("Gene");set.add("Elizabeth");

    set.add("Clara");System.out.println(set);Set sortedSet = new TreeSet(set);System.out.println(sortedSet);

    }}

    http://java.sun.com/products/jdk/1.2/docs/api/java/lang/Object.html#hashCode()http://java.sun.com/developer/onlineTraining/collections/Collection.html#Sortinghttp://java.sun.com/products/jdk/1.2/docs/api/java/lang/Object.html#hashCode()http://java.sun.com/developer/onlineTraining/collections/Collection.html#Sorting
  • 8/2/2019 Core Collections) Intervw Questns

    10/72

    Running the program produces the following output. Notice that the duplicateentry is only present once, and the second list output is sorted.

    [Gene, Clara, Bernadine, Elizabeth][Bernadine, Clara, Elizabeth, Gene]

    AbstractSet Class

    The AbstractSet class overrides the equals() and hashCode() methods toensure two equal sets return the same hash code. Two sets are equal if theyare the same size and contain the same elements. By definition, the hashcode for a set is the sum of the hash codes for the elements of the set. Thus,no matter what the internal ordering of the sets, two equal sets will report thsame hash code.

    Magercises

    Using a HashSet for a Sparse Bit Set

    Using a TreeSet to provide a sorted JList

    List Interface

    The List interface extends the Collection interface to define an orderedcollection, permitting duplicates. The interface adds position-orientedoperations, as well as the ability to work with just a part of the list.

    http://java.sun.com/products/jdk/1.2/docs/api/java/util/AbstractSet.html#equals(java.lang.Object)http://java.sun.com/products/jdk/1.2/docs/api/java/util/AbstractSet.html#hashCode()http://java.sun.com/developer/onlineTraining/collections/magercises/BitSet/index.htmlhttp://java.sun.com/developer/onlineTraining/collections/magercises/JList/index.htmlhttp://java.sun.com/products/jdk/1.2/docs/api/java/util/AbstractSet.html#equals(java.lang.Object)http://java.sun.com/products/jdk/1.2/docs/api/java/util/AbstractSet.html#hashCode()http://java.sun.com/developer/onlineTraining/collections/magercises/BitSet/index.htmlhttp://java.sun.com/developer/onlineTraining/collections/magercises/JList/index.html
  • 8/2/2019 Core Collections) Intervw Questns

    11/72

    The position-oriented operations include the ability to insert an element orCollection, get an element, as well as remove or change an element.Searching for an element in a List can be started from the beginning or endand will report the position of the element, if found.

    void add(int index, Object element)

    boolean addAll(int index, Collection collection)

    Object get(int index)

    int indexOf(Object element)

    int lastIndexOf(Object element)

    Object remove(int index)

    Object set(int index, Object element)

    The List interface also provides for working with a subset of the collection, aswell as iterating through the entire list in a position friendly manner:

    ListIterator listIterator()

    ListIterator listIterator(int startIndex)

    List subList(int fromIndex, int toIndex)

    In working with subList(), it is important to mention that the element atfromIndex is in the sub list, but the element at toIndex is not. This looselymaps to the following for-loop test cases:

    for (int i=fromIndex; i

  • 8/2/2019 Core Collections) Intervw Questns

    12/72

    The following source code demonstrates the looping backwards through a listNotice that the ListIterator is originally positioned beyond the end of the list[list.size()], as the index of the first element is 0.

    List list = ...;ListIterator iterator = list.listIterator(list.size());while (iterator.hasPrevious()) {

    Object element = iterator.previous();// Process element

    }

    Normally, one doesn't use a ListIterator to alternate between going forwardand backward in one iteration through the elements of a collection. Whiletechnically possible, one needs to know that calling next() immediately afterprevious() results in the same element being returned. The same thinghappens when you reverse the order of the calls to next() and previous().

    The add() operation requires a little bit of explanation, also. Adding anelement results in the new element being added immediately prior to theimplicit cursor. Thus, calling previous() after adding an element would returnthe new element and calling next() would have no effect, returning whatwould have been the next element prior to the add operation.

    ArrayList, LinkedList Classes

    There are two general-purpose List implementations in the Collections

    Framework: ArrayList and LinkedList. Which of the two List implementationsyou use depends on your specific needs. If you need to support randomaccess, without inserting or removing elements from any place other than theend, than ArrayList offers the optimal collection. If, however, you need tofrequently add and remove elements from the middle of the list and onlyaccess the list elements sequentially then LinkedList offers the betterimplementation.

  • 8/2/2019 Core Collections) Intervw Questns

    13/72

    Both ArrayList and LinkedList implement the Cloneable interface. In addition,LinkedList adds several methods for working with the elements at the ends ofthe list (only the new methods are shown in the following diagram):

    By using these new methods, you can easily treat the LinkedList as a stack,queue, or other end-oriented data structure.

    LinkedList queue = ...;queue.addFirst(element);Object object = queue.removeLast();LinkedList stack = ...;stack.addFirst(element);Object object = stack.removeFirst();

    The Vector and Stack classes are historical implementations of the Listinterface. They will be discussed later.

    List Usage Example

    The following program demonstrates the use of the concrete List classes. Thefirst part creates a List backed by an ArrayList. After filling the list, specificentries are retrieved. The LinkedList part of the example treats the LinkedListas a queue, adding things at the beginning of the queue and removing themfrom the end.

    import java.util.*;

    public class ListExample {

    public static void main(String args[]) {List list = new ArrayList();list.add("Bernadine");list.add("Elizabeth");list.add("Gene");list.add("Elizabeth");list.add("Clara");System.out.println(list);

    http://java.sun.com/developer/onlineTraining/collections/Collection.html#VectorAndStackClasseshttp://java.sun.com/developer/onlineTraining/collections/Collection.html#VectorAndStackClasses
  • 8/2/2019 Core Collections) Intervw Questns

    14/72

    System.out.println("2: " + list.get(2));System.out.println("0: " + list.get(0));LinkedList queue = new LinkedList();queue.addFirst("Bernadine");queue.addFirst("Elizabeth");queue.addFirst("Gene");

    queue.addFirst("Elizabeth");queue.addFirst("Clara");System.out.println(queue);queue.removeLast();queue.removeLast();System.out.println(queue);

    }}

    Running the program produces the following output. Notice that, unlike Set,List permits duplicates.

    [Bernadine, Elizabeth, Gene, Elizabeth, Clara]2: Gene0: Bernadine[Clara, Elizabeth, Gene, Elizabeth, Bernadine][Clara, Elizabeth, Gene]

    AbstractList and AbstractSequentialList Classes

    There are two abstract List implementations classes: AbstractList andAbstractSequentialList. Like the AbstractSet class, they override the equals()and hashCode() methods to ensure two equal collections return the samehash code. Two sets are equal if they are the same size and contain the sameelements in the same order. The hashCode() implementation is specified inthe List interface definition and implemented here.

    Besides the equals() and hashCode() implementations, AbstractList andAbstractSequentialList provide partial implementations of the remaining Listmethods. They make the creation of concrete list implementations easier, forrandom-access and sequential-access data sources, respectively. Which set omethods you need to define depends on the behavior you wish to support. Thfollowing table should help you remember which methods need to beimplemented. One thing you'll neverneed to provide yourself is animplementation of the Iterator iterator() method.

  • 8/2/2019 Core Collections) Intervw Questns

    15/72

    AbstractList AbstractSequentialList

    unmodifiableObject get(int index)int size()

    ListIterator listIterator(intindex)- boolean hasNext()- Object next()- int nextIndex()

    - boolean hasPrevious()- Object previous()- int previousIndex()int size()

    modifiableunmodifiable +Object set(int index, Objectelement)

    unmodifiable +ListIterator- set(Object element)

    variable-sizeandmodifiable

    modifiable +add(int index, Object element)Object remove(int index)

    modifiable +ListIterator

    - add(Object element)- remove()

    As the Collection interface documentation states, you should also provide twoconstructors, a no-argument one and one that accepts another Collection.

    Magercise

    Using an ArrayList with a JComboBox

    Map InterfaceThe Map interface is not an extension of the Collection interface. Instead, theinterface starts off its own interface hierarchy, for maintaining key-valueassociations. The interface describes a mapping from keys to values, withoutduplicate keys, by definition.

    http://java.sun.com/developer/onlineTraining/collections/magercises/ComboBox/index.htmlhttp://java.sun.com/developer/onlineTraining/collections/magercises/ComboBox/index.html
  • 8/2/2019 Core Collections) Intervw Questns

    16/72

    The interface methods can be broken down into three sets of operations:altering, querying, and providing alternative views.

    The alteration operations allow you to add and remove key-value pairs fromthe map. Both the key and value can be null. However, you should not add aMap to itself as a key or value.

    Object put(Object key, Object value)

    Object remove(Object key)

    void putAll(Map mapping)

    void clear()

    The query operations allow you to check on the contents of the map:

    Object get(Object key)

    boolean containsKey(Object key)

    boolean containsValue(Object value)

    int size()

    boolean isEmpty()

    The last set of methods allow you to work with the group of keys or values asa collection.

    public Set keySet()

    public Collection values()

    public Set entrySet()

    Since the collection of keys in a map must be unique, you get a Set back.Since the collection of values in a map may not be unique, you get aCollection back. The last method returns a Set of elements that implement thMap.Entry interface, described next.

    Map.Entry Interface

    The entrySet() method ofMap returns a collection of objects that implementMap.Entry interface. Each object in the collection is a specific key-value pair ithe underlying Map.

  • 8/2/2019 Core Collections) Intervw Questns

    17/72

    Iterating through this collection, you can get the key or value, as well aschange the value of each entry. However, the set of entries becomes invalid,causing the iterator behavior to be undefined, if the underlying Map ismodified outside the setValue() method of the Map.Entry interface.

    HashMap, TreeMap Classes

    The Collections Framework provides two general-purpose Mapimplementations: HashMap and TreeMap . As with all the concreteimplementations, which implementation you use depends on your specific

    needs. For inserting, deleting, and locating elements in a Map, the HashMapoffers the best alternative. If, however, you need to traverse the keys in asorted order, then TreeMap is your better alternative. Depending upon thesize of your collection, it may be faster to add elements to a HashMap, thenconvert the map to a TreeMap for sorted key traversal. Using a HashMaprequires that the class of key added have a well-defined hashCode()implementation. With the TreeMap implementation, elements added to themap must be sortable. Again, more on sorting later.

    To optimize HashMap space usage, you can tune the initial capacity and loadfactor. The TreeMap has no tuning options, as the tree is always balanced.

    Both HashMap and TreeMap implement the Cloneable interface.

    The Hashtable and Properties classes are historical implementations of theMap interface. They will be discussed later.

    Map Usage Example

    The following program demonstrates the use of the concrete Map classes. Theprogram generates a frequency count of words passed from the commandline. A HashMap is initially used for data storage. Afterwards, the map isconverted to a TreeMap to display the key list sorted.

    import java.util.*;

    public class MapExample {

    http://java.sun.com/developer/onlineTraining/collections/Collection.html#Sortinghttp://java.sun.com/developer/onlineTraining/collections/Collection.html#DictionaryHashtablePropertiesClasseshttp://java.sun.com/developer/onlineTraining/collections/Collection.html#Sortinghttp://java.sun.com/developer/onlineTraining/collections/Collection.html#DictionaryHashtablePropertiesClasses
  • 8/2/2019 Core Collections) Intervw Questns

    18/72

    public static void main(String args[]) {Map map = new HashMap();Integer ONE = new Integer(1);for (int i=0, n=args.length; i

  • 8/2/2019 Core Collections) Intervw Questns

    19/72

    By definition, the hash code for a map is the sum of the hash codes for theelements of the map, where each element is an implementation of theMap.Entry interface. Thus, no matter what the internal ordering of the maps,two equal maps will report the same hash code.

    WeakHashMap Class

    A WeakHashMap is a special-purpose implementation ofMap for storing onlyweak references to the keys. This allows for the key-value pairs of the map tobe garbage collected when the key is no longer referenced outside of theWeakHashMap. Using WeakHashMap is beneficial for maintaining registry-likedata structures, where the utility of an entry vanishes when its key is nolonger reachable by any thread.

    The Java 2 SDK, Standard Edition, version 1.3 adds a constructor toWeakHashMap that accepts a Map. With version 1.2 of the Java 2 platform,the available constructors only permit overriding the default load factor andinitial capacity setting, not initializing the map from another map (asrecommended by the Map interface documentation).

    Sorting

    There have been many changes to the core Java libraries to add support forsorting with the addition of the Collections Framework to the Java 2 SDK,version 1.2. Classes like String and Integer now implement the Comparableinterface to provide a natural sorting order. For those classes without a

    natural order, or when you desire a different order than the natural order, yocan implement the Comparator interface to define your own.

    To take advantage of the sorting capabilities, the Collections Frameworkprovides two interfaces that use it: SortedSet and SortedMap.

    Comparable Interface

    The Comparable interface, in thejava.lang package, is for when a class has anatural ordering. Given a collection of objects of the same type, the interface

    allows you to order the collection into that natural ordering.

    The compareTo() method compares the current instance with an elementpassed in as an argument. If the current instance comes before the argumenin the ordering, a negative value is returned. If the current instance comesafter, then a positive value is returned. Otherwise, zero is returned. It is not

  • 8/2/2019 Core Collections) Intervw Questns

    20/72

    requirement that a zero return value signifies equality of elements. A zeroreturn value just signifies that two objects are ordered at the same position.

    There are fourteen classes in the Java 2 SDK, version 1.2, that implementsthe Comparable interface. The following table shows their natural ordering.While some classes share the same natural ordering, you can only sort classethat are mutually comparable. For the current release of the SDK, that meanthe same class.

    Class Ordering

    BigDecimalBigIntegerByteDoubleFloat

    IntegerLongShort

    Numerical

    Character Numerical by Unicode value

    CollationKey Locale-sensitive string ordering

    Date Chronological

    FileNumerical by Unicode value of characters in fully-qualified,system-specific pathname

    ObjectStreamField Numerical by Unicode value of characters in nameString Numerical by Unicode value of characters in string

    The documentation for the compareTo() method ofString defines the orderinlexicographically. What this means is the comparison is of the numericalvalues of the characters in the text, which is not necessarily alphabetically inall languages. For locale-specific ordering, use Collator with CollationKey.

    The following demonstrates the use ofCollator with CollationKey to do alocale-specific sorting:

    import java.text.*;import java.util.*;

    public class CollatorTest {public static void main(String args[]) {Collator collator =

    Collator.getInstance();

  • 8/2/2019 Core Collections) Intervw Questns

    21/72

    CollationKey key1 =collator.getCollationKey("Tom");

    CollationKey key2 =collator.getCollationKey("tom");

    CollationKey key3 =collator.getCollationKey("thom");

    CollationKey key4 =collator.getCollationKey("Thom");

    CollationKey key5 =collator.getCollationKey("Thomas");

    Set set = new TreeSet();set.add(key1);set.add(key2);set.add(key3);

    set.add(key4);set.add(key5);printCollection(set);

    }static private void printCollection(

    Collection collection) {boolean first = true;Iterator iterator = collection.iterator();System.out.print("[");

    while (iterator.hasNext()) {if (first) {

    first = false;} else {

    System.out.print(", ");}CollationKey key =

    (CollationKey)iterator.next();System.out.print(key.getSourceString());

    }System.out.println("]");

    }}

    Running the program produces the following output:

    [thom, Thom, Thomas, tom, Tom]

  • 8/2/2019 Core Collections) Intervw Questns

    22/72

    If the names were stored directly, without using Collator, then the lowercasenames would appear apart from the uppercase names:

    [Thom, Thomas, Tom, thom, tom]

    Making your own class Comparable is just a matter of implementing thecompareTo() method. It usually involves relying on the natural ordering ofseveral data members. Your own classes should also override equals() andhashCode() to ensure two equal objects return the same hash code.

    Comparator Interface

    When a class wasn't designed to implementjava.lang.Comparable, you canprovide your ownjava.util.Comparator. Providing your own Comparator alsoworks if you don't like the default Comparable behavior.

    The return values of the compare() method ofComparator are similar to thecompareTo() method ofComparable. In this case, if the first element comesbefore the second element in the ordering, a negative value is returned. If thfirst element comes after, then a positive value is returned. Otherwise, zero ireturned. Similar to Comparable, a zero return value does not signify equalityof elements. A zero return value just signifies that two objects are ordered at

    the same position. Its up to the user of the Comparator to determine how todeal with it. If two unequal elements compare to zero, you should first be surthat is what you want and second document the behavior. Using a Comparatothat is not compatible to equals can be deadly when used with a TreeSet orTreeMap. With a set, only the first will be added. With a map, the value for thsecond will replace the value for the second (keeping the key of the first).

    To demonstrate, you may find it easier to write a new Comparator thatignores case, instead of using Collator to do a locale-specific, case-insensitive

    comparison. The following is one such implementation:

    class CaseInsensitiveComparator implementsComparator {public int compare(Object element1,

    Object element2) {String lowerE1 = ((String)element1).toLowerCase();

  • 8/2/2019 Core Collections) Intervw Questns

    23/72

    String lowerE2 = ((String)element2).toLowerCase();

    return lowerE1.compareTo(lowerE2);}

    }

    Since every class subclasses Object at some point, it is not a requirement thayou implement the equals() method. In fact, in most cases you won't. Do keein mind the equals() method checks for equality ofComparatorimplementations, not the objects being compared.

    The Collections class has one predefined Comparator available for reuse.Calling Collections.reverseOrder() returns a Comparator that sorts objects thaimplement the Comparable interface in reverse order.

    Magercise

    Using a Map to Count Words

    SortedSet Interface

    The Collections Framework provides a special Set interface for maintainingelements in a sorted order: SortedSet.

    The interface provides access methods to the ends of the set as well as tosubsets of the set. When working with subsets of the list, changes to the

    subset are reflected in the source set. In addition, changes to the source setare reflected in the subset. This works because subsets are identified byelements at the end points, not indices. In addition, if the fromElement is parof the source set, it is part of the subset. However, if the toElement is part ofthe source set, it is not part of the subset. If you would like a particular to-element to be in the subset, you must find the next element. In the case of aString, the next element is the same string with a null character appended(string+"\0").;

    http://java.sun.com/developer/onlineTraining/collections/magercises/WordCount/index.htmlhttp://java.sun.com/developer/onlineTraining/collections/magercises/WordCount/index.html
  • 8/2/2019 Core Collections) Intervw Questns

    24/72

    The elements added to a SortedSet must either implement Comparable or yomust provide a Comparator to the constructor of its implementation class:TreeSet. (You can implement the interface yourself. But the CollectionsFramework only provides one such concrete implementation class.)

    To demonstrate, the following example uses the reverse order Comparatoravailable from the Collections class:

    Comparator comparator = Collections.reverseOrder();Set reverseSet = new TreeSet(comparator);reverseSet.add("Bernadine");reverseSet.add("Elizabeth");reverseSet.add("Gene");reverseSet.add("Elizabeth");reverseSet.add("Clara");

    System.out.println(reverseSet);

    Running the program produces the following output:

    [Gene, Elizabeth, Clara, Bernadine]

    Because sets must hold unique items, if comparing two elements when addinan element results in a zero return value (from either the compareTo()method ofComparable or the compare() method ofComparator), then thenew element is not added. If the elements are equal, then that is okay.However, if they are not, then you should modify the comparison method sucthat the comparison is compatible with equals().

    Using the prior CaseInsensitiveComparator to demonstrate this problem, thefollowing creates a set with three elements: thom, Thomas, and Tom, not fivelements as might be expected.

    Comparator comparator =new CaseInsensitiveComparator();

    Set set = new TreeSet(comparator);set.add("Tom");set.add("tom");set.add("thom");set.add("Thom");set.add("Thomas");

  • 8/2/2019 Core Collections) Intervw Questns

    25/72

    SortedMap Interface

    The Collections Framework provides a special Map interface for maintainingkeys in a sorted order: SortedMap.

    The interface provides access methods to the ends of the map as well as tosubsets of the map. Working with a SortedMap is just like a SortedSet, excep

    the sort is done on the map keys. The implementation class provided by theCollections Framework is a TreeMap.

    Because maps can only have one value for every key, if comparing two keyswhen adding a key-value pair results in a zero return value (from either thecompareTo() method ofComparable or the compare() method ofComparator), then the value for the original key is replaced with the newvalue. If the elements are equal, then that is okay. However, if they are not,then you should modify the comparison method such that the comparison is

    compatible with equals().

    Special Collection Implementations

    To keep the Collections Framework simple, added functionality is provided bywrapper implementations (also known as the Decorator design pattern--seethe Design Patterns book for more information on patterns). These wrappersdelegate the collections part to the underlying implementation class, but theyadd functionality on top of the collection. These wrappers are all providedthrough the Collections class. The Collections class also provides support for

    creating special-case collections.

    Read-Only Collections

    After you've added all the necessary elements to a collection, it may beconvenient to treat that collection as read-only, to prevent the accidentalmodification of the collection. To provide this capability, the Collections classprovides six factory methods, one for each ofCollection, List, Map, Set,SortedMap, and SortedSet.

    http://hillside.net/patterns/DPBook/DPBook.htmlhttp://hillside.net/patterns/DPBook/DPBook.html
  • 8/2/2019 Core Collections) Intervw Questns

    26/72

    Collection unmodifiableCollection(Collection collection)

    List unmodifiableList(List list)

    Map unmodifiableMap(Map map)

    Set unmodifiableSet(Set set)

    SortedMap unmodifiableSortedMap(SortedMap map)

    SortedSet unmodifiableSortedSet(SortedSet set)

    Once you've filled the collection, the best way to make the collection read-onis to replace the original reference with the read-only reference. If you don'treplace the original reference, then the collection is not read-only, as you canstill use the original reference to modify the collection. The following programdemonstrates the proper way to make a collection read-only. In addition, itshows what happens when you try to modify a read-only collection.

    import java.util.*;

    public class ReadOnlyExample {public static void main(String args[]) {Set set = new HashSet();set.add("Bernadine");

    set.add("Elizabeth");set.add("Gene");set.add("Elizabeth");set = Collections.unmodifiableSet(set);set.add("Clara");

    }}

    When run and the last add() operation is attempted on the read-only set, anUnsupportedOperationException is thrown.

    Thread-Safe Collections

    The key difference between the historical collection classes and the newimplementations within the Collections Framework is the new classes are notthread-safe. This was done such that if you don't need the synchronization,you don't use it, and everything works much faster. If, however, you are usina collection in a multi-threaded environment, where multiple threads can

  • 8/2/2019 Core Collections) Intervw Questns

    27/72

    modify the collection simultaneously, the modifications need to besynchronized. The Collections class provides for the the ability to wrap existincollections into synchronized ones with another set of six methods:

    Collection synchronizedCollection(Collection collection)

    List synchronizedList(List list)

    Map synchronizedMap(Map map)

    Set synchronizedSet(Set set)

    SortedMap synchronizedSortedMap(SortedMap map)

    SortedSet synchronizedSortedSet(SortedSet set)

    Unlike when making a collection read-only, you synchronize the collection

    immediately after creating it. You also must make sure you do not retain areference to the original collection, or else you can access the collectionunsynchronized. The simplest way to make sure you don't retain a reference to never create one:

    Set set = Collection.synchronizedSet(new HashSet());

    Making a collection unmodifiable also makes a collection thread-safe, as thecollection can't be modified. This avoids the synchronization overhead.

    Singleton Collections

    The Collections class provides for the ability to create single element setsfairly easily. Instead of having to create the Set and fill it in separate steps,you can do it all at once. The resulting Set is immutable.

    Set set = Collection.singleton("Hello");

    The Java 2 SDK, Standard Edition, version 1.3 adds the ability to createsingleton lists and maps, too:

    List singletonList(Object element)

    Map singletonMap(Object key, Object value)

    Multiple Copy Collections

    If you need an immutable list with multiple copies of the same element, thenCopies(int n, Object element) method of the Collections class returns justsuch the List:

  • 8/2/2019 Core Collections) Intervw Questns

    28/72

    List fullOfNullList = Collection.nCopies(10, null);

    By itself, that doesn't seem too useful. However, you can then make the listmodifiable by passing it along to another list:

    List anotherList = new ArrayList(fullOfNullList);

    This now creates 10 element ArrayList, where each element is null. You can

    now modify each element at will, as it becomes appropriate.

    Empty Collections

    The Collections class also provides constants for empty collections:

    List EMPTY_LIST

    Set EMPTY_SET

    The Java 2 SDK, Standard Edition, version 1.3 has a predefined empty mapconstant:

    Map EMPTY_MAP

    Historical Collection Classes

    While this course is about the new Collections Framework of the Java 2 SDK,there are times when you still need to use some of the original collectionscapabilities. The following reviews some of the capabilities of working witharrays, vectors, hashtables, enumerations, and other historical capabilities.

    Arrays

    One learns about arrays fairly early on when learning the Java programminglanguage. Arrays are defined to be fixed-size collections of the same datatypeThey are the only collection that supports storing primitive datatypes.Everything else, including arrays, can store objects. When creating an array,you specify both the number and type of object you wish to store. And, overthe life of the array, it can neither grow nor store a different type (unless itextends the first type).

    To find out the size of an array, you ask its single public instance variable,length, as in array.length.

    To access a specific element, either for setting or getting, you place theinteger argument within square brackets ([int]), either before orafter thearray reference variable. The integer index is zero-based, and accessingbeyond either end of the array will thrown an

  • 8/2/2019 Core Collections) Intervw Questns

    29/72

    ArrayIndexOutOfBoundsException at runtime. If, however, you use a longvariable to access an array index, you'll get a compiler-time error.

    Arrays are full-fledged subclasses ofjava.lang.Object. They can be used withthe various Java programming language constructs excepting an object:

    Object obj = new int[5];if (obj instanceof int[]) {// true

    }if (obj.getClass().isArray()) {

    // true}

    When created, arrays are automatically initialized, either to false for a booleaarray , null for an Object array, or the numerical equivalent of 0 for everythinelse.

    To make a copy of an array, perhaps to make it larger, you use thearraycopy() method ofSystem. You need to preallocate the space in thedestination array.

    System.arraycopy(Object sourceArray, int sourceStartPosition, Object

    destinationArray, int destinationStartPosition, int length)

    Vector and Stack Classes

    A Vector is an historical collection class that acts like a growable array, butcan store heterogeneous data elements. With the Java 2 SDK, version 2, theVector class has been retrofitted into the Collections Framework hierarchy toimplement the List interface. However, if you are using the new framework,you should use ArrayList, instead.

    When transitioning from Vector to ArrayList, one key difference is thearguments have been reversed to positionally change an element's value:

    From original Vector classvoid setElementAt(Object element, int index)

    From List interfacevoid set(int index, Object element)

  • 8/2/2019 Core Collections) Intervw Questns

    30/72

    The Stack class extends Vector to implement a standard list-in-first-out (LIFOstack, with push() and pop() methods. Be careful though. Since the Stackclass extends the Vector class, you can still access or modify a Stack with theinherited Vector methods.

    Enumeration Interface

    The Enumeration interface allows you to iterator through all the elements of acollection. In the Collections Framework, this interface has been supercededby the Iterator interface. However, not all libraries supports the newerinterface, so you may find yourself using Enumeration from time to time.

    Iterating through an Enumeration is similar to iterating through an Iterator,though some people like the method names better with Iterator. However,there is no removal support with Enumeration.

    Enumeration enum = ...;while (enum.hasNextElement()) {

    Object element = iterator.nextElement();// process element

    }

    Dictionary, Hashtable, Properties ClassesThe Dictionary class is completely full of abstract methods. In other words, itshould have been an interface. It forms the basis for key-value pair collectionin the historical collection classes, with its replacement being Map, in the newframework. Hashtable and Properties are the two specific implementations ofDictionary available.

    The Hashtable implementation is a generic dictionary that permits storing anyobject as its key or value (besides null). With the Java 2 SDK, version 1.2, Th

    class has been reworked into the Collections Framework to implement the Mainterface. So, when using, you can use the original Hashtable methods or thenewer Map methods. If you need a synchronized Map, using Hashtable isslightly faster than using a synchronized HashMap.

    The Properties implementation is a specialized Hashtable for working with texstrings. While you have to cast valued retrieved from a Hashtable to yourdesired class, the Properties class allows you to get text values withoutcasting. The class also supports loading and saving property settings from an

  • 8/2/2019 Core Collections) Intervw Questns

    31/72

    input stream or to a output stream. The most commonly used set ofproperties is the system properties list, retrieved by System.getProperties().

    BitSet Class

    A BitSet represents an alternate representation of a set. Given a finite numbeofn objects, you can associate a unique integer with each object. Then eachpossible subset of the objects corresponds to an n-bit vector, with each bit"on" or "off" depending on whether the object is in the subset. For smallvalues ofn a bit vector might be an extremely compact representation.However, for large values ofn an actual bit vector might be inefficient, whenmost of the bits are off.

    There is no replacement to BitSet in the new framework.

    Magercise

    Using a HashSet for a Sparse Bit Set

    Algorithm Support

    The Collections and Arrays classes, available as part of the CollectionsFramework, provide support for various algorithms with the collection classesboth new and old. The different operations, starting with sorting andsearching, are described next.

    Sorting Arrays

    While the TreeSet and TreeMap classes offer sorted version of sets and mapsthere is no sorted List collection implementation. Also, prior to the collectionsframework, there was no built in support for sorting arrays. As part of theframework, you get both support for sorting a List, as well as support forsorting arrays of anything, including primitives. With any kind of sorting, allitems must be comparable to each other (mutually comparable). If they arenot, a ClassCastException will be thrown.

    Sorting of a List is done with one of two sort() methods in the Collections

    class. If the element type implements Comparable then you would use thesort(List list) version. Otherwise, you would need to provide a Comparator anuse sort(List list, Comparator comparator). Both versions are destructive tothe List and guarantee O(n log2n) performance (or better), including whensorting a LinkedList, using a merge sort variation.

    Sorting of arrays is done with one of eighteen different methods. There aretwo methods for sorting each of the seven primitive types (besides boolean),

    http://java.sun.com/developer/onlineTraining/collections/magercises/BitSet/index.htmlhttp://java.sun.com/developer/onlineTraining/collections/magercises/BitSet/index.html
  • 8/2/2019 Core Collections) Intervw Questns

    32/72

    one for sorting the whole array and one for sorting part of the array. Theremaining four are for sorting object arrays (Object[ ]).

    The sorting of primitive arrays involving just calling Arrays.sort() with yourarray as the argument, and letting the compiler determine which of thefollowing methods to pick:

    void sort(byte array[ ])

    void sort(byte array[ ], int fromIndex, int toIndex)

    void sort(short array[ ])

    void sort(short array[ ], int fromIndex, int toIndex)

    void sort(int array[ ])

    void sort(int array[ ], int fromIndex, int toIndex)

    void sort(long array[ ])

    void sort(long array[ ], int fromIndex, int toIndex)

    void sort(float array[ ])

    void sort(float array[ ], int fromIndex, int toIndex)

    void sort(double array[ ])

    void sort(double array[ ], int fromIndex, int toIndex)

    void sort(char array[ ])

    void sort(char array[ ], int fromIndex, int toIndex)

    The sorting of object arrays is a little more involved, as the compiler doesn't

    check everything for you. If the object in the array implements Comparable,then you can just sort the array directly, in whole or in part. Otherwise, youmust provide a Comparator to do the sorting for you. You can also provide aComparator implementation if you don't like the default ordering.

    void sort(Object array[ ])

    void sort(Object array[ ], int fromIndex, int toIndex)

    void sort(Object array[ ], Comparator comparator)

  • 8/2/2019 Core Collections) Intervw Questns

    33/72

    void sort(Object array[ ], int fromIndex, int toIndex, Comparatorcomparator)

    Searching

    Besides sorting, the Collections and Arrays classes provide mechanisms tosearch a List or array, as well as to find the minimum and maximum valueswithin a Collection.

    While you can use the contains() method ofList to find if an element is part othe list, it assumes an unsorted list. If you've previously sorted the List, usingCollections.sort(), then you can do a much quicker binary search using one othe two overridden binarySearch() methods. If the objects in the Listimplement Comparable, then you don't need to provide a Comparator.Otherwise, you must provide a Comparator. In addition, if you sorted with aComparator, you must use the same Comparator when binary searching.

    public static int binarySearch(List list, Object key)

    public static int binarySearch(List list, Object key, Comparator comparator)

    If the List to search subclasses the AbstractSequentialList class (likeLinkedList), then a sequential search is actually done.

    Array searching works the same way. After using one of the Arrays.sort()methods, you can take the resulting array and search for an element. There

    are seven overridden varieties ofbinarySearch() to search for a primitive (allbut boolean), and two to search an Object array, both with and without aComparator.

    If the original List or array is unsorted, the result is non-deterministic.

    Besides searching for specific elements within a List, you can search forextreme elements within any Collection: the minimum and maximum. If youknow your collection is already sorted, just get the first or last element.

    However, for unsorted collections, you can use one of the min() or max()methods ofCollections. If the object in the collection doesn't implementComparable, then you must provide a Comparator.

    Object max(Collection collection)

    Object max(Collection collection, Comparator comparator)

    Object min(Collection collection)

  • 8/2/2019 Core Collections) Intervw Questns

    34/72

    Object min(Collection collection, Comparator comparator)

    Checking Equality

    While the MessageDigest class always provided an isEqual() method tocompare two byte arrays, it never felt right to use it to compare byte arraysunless they were from message digests. Now, with the help of the Arraysclass, you can check for equality of any array of primitive or object type. Twoarrays are equal if they contain the same elements in the same order.Checking for equality with arrays of objects relies on the equals() method ofeach object to check for equality.

    byte array1[] = ...;byte array2[] = ...;if (Arrays.equals(array1, array2) {

    // They're equal}

    Manipulating

    The Collections and Arrays classes offer several ways of manipulating theelements within a List or array. There are no additional ways to manipulatethe other key framework interfaces (Set and Map).

    With a List, the Collections class lets you replace every element with a singleelement, copy an entire list to another, reverse all the elements, or shufflethem around. When copying from one list to another, if the destination list is

    larger, the remaining elements are untouched.

    void fill(List list, Object element)

    void copy(List source, List destination)

    void reverse(List list)

    void shuffle(List list)

    void shuffle(List list, Random random)

    The Arrays class allows you to replace an entire array or part of an array withone element via eighteen overridden versions of the fill() method. All themethods are of the form fill(array, element) or fill(array, fromIndex, toIndex,element).

    Big-O Notation

  • 8/2/2019 Core Collections) Intervw Questns

    35/72

    Performance of sorting and searching operations with collections of size n ismeasured using Big-O notation. The notation describes the complexity of thealgorithm in relation to the maximum time in which an algorithm operates, folarge values ofn. For instance, if you iterate through an entire collection tofind an element, the Big-O notation is referred to as O(n), meaning that as nincreases, time to find an element in a collection of size n increases linearly.This demonstrates that Big-O notation assumes worst case performance. It isalways possible that performance is quicker.

    The following table shows the Big-O values for different operations, with65,536 as the value for n. In addition, the operation count shows that if youare going to perform multiple search operations on a collection, it is faster todo a quick sort on the collection, prior to searching, versus doing a linearsearch each time. (And, one should avoid bubble sorting, unless n is reallysmall!)

    Description Big-O # Operations Example

    Constant O(1) 1 Hash table lookup (ideal)

    Logarithmic O(log2n) 16Binary search on sortedcollection

    Linear O(n) 65,536 Linear search

    Linear-logarithmic O(n log2n) 1,048,576 Quick sort

    Quadratic O(n2) 4,294,967,296 Bubble sort

    Legend: n = 65536

    Usage Issues

    The Collections Framework was designed such that the new framework classeand the historical data structure classes can interoperate. While it is good ifyou can have all your new code use the new framework, sometimes you can'The framework provides much support for intermixing the two sets of

    collections. In addition, you can develop with a subset of the capabilities withJDK 1.1.

    Converting from Historical Collections to New Collections

    There are convenience methods for converting from many of the originalcollection classes and interfaces to the newer framework classes andinterfaces. They serve as bridges when you need a new collection but have ahistorical collection. You can go from an array or Vector to a List, a Hashtableto a Map, or an Enumeration to any Collection.

  • 8/2/2019 Core Collections) Intervw Questns

    36/72

    For going from any array to a List, you use the asList(Object array[]) methodof the Arrays class. Changes to the List pass through to the array, but youcannot adjust the size of the array.

    String names[] = {"Bernadine","Elizabeth", "Gene", "Clara"};

    List list = Arrays.asList(names);

    Because the original Vector and Hashtable classes have been retrofitted intothe new framework, as a List and Map respectively, there is no work to treateither of these historical collections as part of the new framework. Treating aVector as a List automatically carries to its subclass Stack. Treating aHashtable as a Map automatically caries to its subclass Properties.

    Moving an Enumeration to something in the new framework requires a littlemore work, as nothing takes an Enumeration in its constructor. So, to converan Enumeration, you create some implementation class in the new frameworand add each element of the enumeration.

    Enumeration enumeration = ...;Collection collection = new LinkedList();while (e.hasMoreElements()) {

    collection.add(e.nextElement());}// Operate on collection

    Converting from New Collections to Historical Collections

    In addition to supporting the use of the old collection classes within the newcollection framework, there is also support for using the new framework andstill using libraries that only support the original collections. You can easilyconvert from Collection to array, Vector, or Enumeration, as well as from Mapto Hashtable.

    There are two ways to go from Collection to array, depending upon the type oarray you need. The simplest way involves going to an Object array. Inaddition, you can also convert the collection into any other array of objects.However, you cannot directly convert the collection into an array of primitivesas collections must hold objects.

    To go from a collection to an Object[], you use the toArray() method ofCollection:

  • 8/2/2019 Core Collections) Intervw Questns

    37/72

    Collection collection = ...;Object array[] = collection.toArray();

    The toArray() method is overridden to accept an array for placing theelements of the collection: toArray(Object array[]). The datatype of theargument determines the type of array used to stored the collection andreturned by the method. If the array isn't large enough, a new array of the

    appropriate type will be created.

    Collection collection = ...;int size = collection.size();Integer array[] =

    collection.toArray(new Integer[size]);

    To go from Collection to Vector, the Vector class now includes a constructorthat accepts a Collection. As with all these conversions, if the element in theoriginal conversion is mutable, then no matter from where it is retrieved and

    modified, its changed everywhere.

    Dimension dims[] = {new Dimension (0,0),new Dimension (0,0)};

    List list = Arrays.asList(dims);Vector v = new Vector(list);Dimension d = (Dimension)v.get(1);d.width = 12;

    Going from Collection to Enumeration is much easier than going fromEnumeration to Collection. The Collections class includes a static method to dthe conversion for you:

    Collection collection = ...;Enumeration enum =

    Collections.enumeration(collection);

    The conversion from Map to Hashtable is similar to Collection to Vector, justpass the new framework class to the constructor. After the conversion,changing the value for the key in one does not alter the value for the key inthe other.

    Map map = ...;Hashtable hashtable = new Hashtable(map);

    Working with the Collections Framework Support in JDK 1.1

  • 8/2/2019 Core Collections) Intervw Questns

    38/72

    If you are still using JDK 1.1, you can start taking advantage of the CollectionFramework today. Sun Microsystems provides a subset of the collections APIfor use with JDK 1.1. The interfaces and classes of the framework have beenmoved from thejava.lang andjava.util package to the non-corecom.sun.java.util.collections package. This is not a complete set of classeschanged to support the framework, but only copies of those introduced.Basically, what that means is none of the system classes are sortable bydefault, you must provide your own Comparator.

    The following table lists the classes available in the Collections Frameworkrelease for JDK 1.1. In some cases, there will be two differentimplementations of the same class, like with Vector, as the 1.2 frameworkversion implements List and the core 1.1 version doesn't.

    AbstractCollection AbstractList

    AbstractMap AbstractSequentialListAbstractSet ArrayList

    Arrays Collection

    Collections Comparable

    Comparator ConcurrentModificationException

    HashMap HashSet

    Hashtable Iterator

    LinkedList List

    ListIterator Map

    NoSuchElementException Random

    Set SortedMap

    SortedSet TreeMap

    TreeSet UnsupportedOperationException

    Vector

    Alternative Collections

    Because the Collection Framework was not available prior to the introductionof the Java 2 platform, several alternative collection libraries becameavailable. Two such libraries are Doug Lea's Collections Package andObjectSpace's JGL.

    Doug Lea's Collections Package.

    http://java.sun.com/javase/technologies/desktop/javabeans/infobus/index.jsp#COLLECTIONShttp://java.sun.com/javase/technologies/desktop/javabeans/infobus/index.jsp#COLLECTIONS
  • 8/2/2019 Core Collections) Intervw Questns

    39/72

    10 example of using ArrayList in Java >>> Java ArrayList Tutorial

    Please vote +1 if you like this post

    ArrayList in Java is most frequently used collection class after HashMap in

    Java. Java ArrayList represents an automatic resizable array and used in

    place of array. Since we can not modify size of an array after creating it, we

    prefer to use ArrayList in Java which re-size itself automatically once it gets

    full. ArrayList in Java implements List interface and allow null. Java

    ArrayList also maintains insertion order of elements and allows duplicates

    opposite to any Set implementation which doesn't allow duplicates. ArrayListsupports both Iterator and ListIterator for iteration but its recommended to

    use ListIterator as it allows the programmer to traverse the list in either

    direction, modify the list during iteration, and obtain the iterator's current

    position in the list. But while using ListIterator you need to be little careful

    because ListIterator has no current element; its cursor position always lies

    between the element that would be returned by a call to previous () and the

    element that would be returned by a call to next (). In thisJava ArrayList

    tutorialwe will see how to createJava ArrayListand perform various

    operations on Java ArrayList.

    ArrayList has been modified in Java5 (Tiger) to support Generics which make

    Java ArrayList even more powerful because of enhanced type-safety. Before

    Java5 since there was no generics no type checking at compile time which

    means there is chance of storing different type ofelement in an ArrayListwhich is meant for something and ultimately results in ClassCastException

    during runtime. with generics you can create Java ArrayList which accepts

    only type of object specified during creation time and results in compilation

    error if someone tries to insert any other object into ArrayList in Java; for

    example if you create an ArrayList of String object you can not store Integer

    on it because add() method of ArrayList will check Type before adding object

    into ArrayList in Java opposite to add() method of Java4 which accepts any

    object.

    http://javarevisited.blogspot.com/2011/05/example-of-arraylist-in-java-tutorial.htmlhttp://javarevisited.blogspot.com/2011/02/how-hashmap-works-in-java.htmlhttp://javarevisited.blogspot.com/2011/02/how-hashmap-works-in-java.htmlhttp://2.bp.blogspot.com/-wrzDeQGAe1I/TWu8pLuLr4I/AAAAAAAAADE/V017G-6Q61w/s1600/java_logo_50_50.jpghttp://javarevisited.blogspot.com/2011/05/example-of-arraylist-in-java-tutorial.htmlhttp://javarevisited.blogspot.com/2011/02/how-hashmap-works-in-java.htmlhttp://javarevisited.blogspot.com/2011/02/how-hashmap-works-in-java.html
  • 8/2/2019 Core Collections) Intervw Questns

    40/72

    Java Arraylist with Generics in JDK 1.5

    Its also important to remember that ArrayList is not synchronized and

    should not be shared between multiple threads. If multiple threads access a

    Java ArrayList instance concurrently, and at least one of the threads modifies

    the list structurally, it must be synchronized externally. (As per Java doc a

    structural modification is any operation that adds or deletes one or more

    elements, or explicitly resizes the backing array; merely setting the value of

    an element is not a structural modification.) This is typically accomplished

    by synchronizing on some object that naturally encapsulates the list. If no

    such object exists, the list should be "wrapped" using the

    Collections.synchronizedList method. Its recommended to synchronize the lis

    at the creation time to avoid any accidental unsynchronized access to the list

    Another better option is to use CopyOnWriteArrayList which is added from

    Java 5 and optimized for multiple concurrent read. In CopyOnWriteArrayListall mutative operations (add, set, and so on) are implemented by making a

    fresh copy of the underlying array and that's why it is called as "CopyOnWrite

    Example of ArrayList in Java

    Let's see some example of creating ArrayList in java and using them, I

    have tried to provide as much example as possible to illustrate different

    operations possible on Java ArrayList. Please let me know if you need any

    other Java ArrayList examples and I will add them here.

    1) Creating an ArrayList

    http://javarevisited.blogspot.com/2011/04/synchronization-in-java-synchronized.htmlhttp://javarevisited.blogspot.com/2010/10/difference-between-hashmap-and.htmlhttp://javarevisited.blogspot.com/2011/04/synchronization-in-java-synchronized.html
  • 8/2/2019 Core Collections) Intervw Questns

    41/72

    You can use ArrayList in Java with or without Generics both are

    permitted by generics version is recommended because of enhanced type-

    safety.

    In this example we will create an ArrayList of String in Java. This Java

    ArrayList will only allow String and will throw compilation error if we try to an

    other object than String.

    ArrayList stringList = new ArrayList();

    2) Putting an Item into ArrayList

    Second line will result in compilation error because this Java ArrayList will

    only allow String elements.stringList.add("Item");

    stringList.add(new Integer(2)); //compilation error

    3) Checking size of ArrayList

    Size of an ArrayList in Java is total number of elements currently stored in

    ArrayList.

    int size = stringList.size();

    4) Checking Index of an Item in Java Arraylist

    You can use indexOf() method of ArrayList in Java to find out index of a

    particular object.

    int index = stringList.indexOf("Item");

    5) Retrieving Item from arrayList in a loop

    http://javarevisited.blogspot.com/2010/10/why-string-is-immutable-in-java.htmlhttp://javarevisited.blogspot.com/2010/10/why-string-is-immutable-in-java.html
  • 8/2/2019 Core Collections) Intervw Questns

    42/72

    Many a times we need to traverse on Java ArrayList and perform some

    operations on each retrieved item. Here are two ways of doing it without usin

    Iterator.

    We will see use of Iterator in next section.

    for (int i = 0; i

    String item = stringList.get(i);

    }

    From Java 5 onwards you can use foreach loop as well

    for(String item: stringList){

    System.out.println("retreived element: " + item);

    }

    6) Checking ArrayList for an Item

    Sometimes we need to check whether an element exists in ArrayList in Java o

    not for this purpose we can use contains () method of Java. contains() methotakes type of object defined in ArrayList creation and returns true if this list

    contains the specified element.

    7) Checking if ArrayList is Empty

    We can use isEmpty() method of Java ArrayList to check whether

    ArrayList is empty. isEmpty() method returns true if this ArrayList contains

    no elements.

    boolean result = stringList.isEmpty();

    8) Removing an Item from ArrayList

  • 8/2/2019 Core Collections) Intervw Questns

    43/72

    There are two ways to remove any elements from ArrayList in Java. You

    can either remove an element based on its index or by providing object itself

    Remove remove (int index) and remove (Object o) method is used to remove

    any element from ArrayList in Java. Since ArrayList allows duplicate its worth

    noting that remove (Object o) removes the first occurrence of the specified

    element from this list, if it is present. In below code first call will remove first

    element from ArrayList while second call will remove first occurrence of item

    from ArrayList in Java.

    stringList.remove(0);

    stringList.remove(item);

    9) Copying data from one ArrayList to another ArrayList in Java

    Many a times you need to create a copy of ArrayList for this purpose you

    can use addAll(Collection c) method of ArrayList in Java to copy all elements

    from on ArrayList to another ArrayList in Java. Below code will add all

    elements of stringList to newly created copyOfStringList.

    ArrayList copyOfStringList = new ArrayList();

    copyOfStringList.addAll(stringList);

    10) Replacing an element at a particular index

    You can use set (int index, E element) method of java ArrayList to replace an

    element from a particular index. Below code will replace first element of

    stringList from "Item" to "Item2".

    stringList.set(0,"Item2");

  • 8/2/2019 Core Collections) Intervw Questns

    44/72

    11) Clearing all data from ArrayList

    ArrayList in Java provides clear () method which removes all ofthe elements

    from this list. Below code will remote all elements from our stringList and

    make the list empty. You can reuse Java ArrayList after clearing it.

    stingList.clear();

    12) Converting from ArrayList to Array in Java

    Java ArrayList provides you facility to get the array back from your

    ArrayList. You can use toArray(T[] a) method returns an array containing all

    the elements in this list in proper sequence (from first to last element). "a" isthe array into which the elements of the list are to be stored, if it is big

    enough; otherwise, a new array of the same runtime type is allocated for this

    purpose.

    String[] itemArray = new String[stringList.size()];

    String[] returnedArray = stringList.toArray(itemArray);

    13) Creating Synchronized ArrayList

    Some times you need to synchronize your ArrayList in java to make it

    shareable between multiple threads you can use Collections utility class for

    this purpose as shown below.

    List list = Collections.synchronizedList(new ArrayList(...));

    14) Creating ArrayList from Array in Java

    ArrayList in Java is amazing you can create even an ArrayList full of your

    element from an already existing array. You need to use Arrays.asList(T... a)

    http://javarevisited.blogspot.com/2011/04/synchronization-in-java-synchronized.htmlhttp://javarevisited.blogspot.com/2011/04/synchronization-in-java-synchronized.html
  • 8/2/2019 Core Collections) Intervw Questns

    45/72

    method for this purpose which returns a fixed-size list backed by the specifie

    array.

    ArrayList stringList = Arrays.asList(new String[]{"One", "Two", "Three");

    15) Traversing in ArrayList in Java

    You can use either Iterator or ListIterator for traversing on Java ArrayList.

    ListIterator will allow you to traverse in both directions while both Iterator an

    ListIterator will allow you to remove elements from ArrayList in Java while

    traversing.

    Iterator itr = stringList.iterator();

    while(itr.hasNext()){

    System.out.println(itr.next());

    }

    ListIterator listItr = stringList.listIterator();

    while(listItr.hasNext()){

    System.out.println(itr.next());

    }

    16) Sorting elements of ArrayList in Java

    You can use Collections.sort(List list) method to sort a Java ArrayList in

    natural order defined by Comparable interface and can use

    Collections.sort(List list, Comparator c) method to sort your Java ArrayList

    based upon provided Comparator.

    http://javarevisited.blogspot.com/2010/10/what-is-difference-between-enumeration.htmlhttp://javarevisited.blogspot.com/2010/10/what-is-difference-between-enumeration.html
  • 8/2/2019 Core Collections) Intervw Questns

    46/72

    Tips on ArrayList in Java

    1) ArrayList is not a synchronized collection hence it is not suitable to be

    used between multiple threads concurrently. If you want to use ArrayList the

    you need to either use new CopyonWriteArrayList or use

    Collections.synchronizedList() to create a synchronized List.

    2) CopyonWriteArrayList is recommended for concurrent multi-threading

    environment as it is optimized for multiple concurrent read and creates copy

    for write operation.

    3) When ArrayList gets full it creates another array and uses

    System.arrayCopy() to copy all elements from one array to another array.

    4) Iterator and ListIterator of java ArrayList are fail-fast it means if

    Arraylist is structurally modified at any time after the Iterator is created, in

    any way except through the iterator's own remove or add methods, the

    Iterator will throw a ConcurrentModificationException. Thus, in the face of

    concurrent modification, the Iterator fails quickly and cleanly, that's why its

    called fail-fast.

    5) ConcurrentModificationException is not guaranteed and it only thrown at

    best effort.

    6) If you are creating Synchronized List its recommended to create whilecreating instance of underlying ArrayList to prevent accidental unsynchronize

    access to the list.

    7) An application can increase the capacity of an ArrayList instance before

    adding a large number of elements using the ensureCapacity operation. This

    may reduce the amount of incremental reallocation due to incremental filling

    of ArrayList.

    8) The size, isEmpty, get, set, Iterator, and ListIterator operations run inconstant time because ArrayList is based on Array but adding or removin

    an element is costly as compared to LinkedList.

    9) ArrayList class is enhanced in Java5 to support Generics which added extra

    type-safety on ArrayList. Its recommended to use generics version of

    ArrayList to ensure that your ArrayList contains only specified type of elemen

    and avoid any ClassCastException.

    http://javarevisited.blogspot.com/2011/04/difference-between-concurrenthashmap.htmlhttp://javarevisited.blogspot.com/2010/10/what-is-difference-between-enumeration.htmlhttp://javarevisited.blogspot.com/2010/10/what-is-difference-between-synchronized.htmlhttp://javarevisited.blogspot.com/2011/04/difference-between-concurrenthashmap.htmlhttp://javarevisited.blogspot.com/2010/10/what-is-difference-between-enumeration.htmlhttp://javarevisited.blogspot.com/2010/10/what-is-difference-between-synchronized.html
  • 8/2/2019 Core Collections) Intervw Questns

    47/72

    10) Since ArrayList implements List interface it maintains insertion order

    of element and allow duplicates.

    11)If we set Arraylist reference null in Java all the elements inside Arraylist

    becomes eligible to garbage collection in java , provided there are no more

    reference exists for those objects.

    Hope this Java ArrayList tutorial will be helpful for beginners in Java

    Examples1. /*2. Java ArrayList example.3. This Java ArrayList example describes the basic operations performed o

    the ArrayList.4. */5.

    6. importjava.util.ArrayList;7. importjava.util.Iterator;8.9. publicclass ArrayListExample{10.11. publicstaticvoid main(String args[]){12.13. // constructs a new empty ArrayList14. ArrayList arrayList = newArrayList();

    http://javarevisited.blogspot.com/2011/04/garbage-collection-in-java.htmlhttp://javadeveloper.co.in/category/java-exampleshttp://javarevisited.blogspot.com/2011/04/garbage-collection-in-java.htmlhttp://javadeveloper.co.in/category/java-examples
  • 8/2/2019 Core Collections) Intervw Questns

    48/72

    15.16. /*17. To specify initial capacity, use following constructor.18. ArrayList ArrayList = new ArrayList(100);19.20. To create ArrayList from Collection use following constructor

    21. ArrayList ArrayList = new ArrayList(Collection collection);22.23. In this case the initial capacity would be 110% of the size o

    the collection.24. */ 25.26. /*27.28. To add value into ArrayList use add() method.29. Signature of the add() method is,30. boolean add(Object object)31.32. The value would be appended to the list.33.34. To insert value into ArrayList at particular index, use35. void add(int index, Object object)36.37. This method will shifts the subsequent elements of the list.38.39. To append all elements of the collection to existing list, use

    40. boolean addAll(Collection c)41.42. To insert all elements of the collection into existing list, use

    43. boolean addAll(int index, Collection collection)44.45. To replace particular element in the ArrayList, use46. Object set(int index, Object value)47.48. It returns the previous element present at the specified index49.50. */ 51.52. arrayList.add(newInteger(1));//adding value to ArrayList53.

  • 8/2/2019 Core Collections) Intervw Questns

    49/72

    54. arrayList.add(newInteger(2));55.56. arrayList.add(newInteger(3));57.58. /*59. IMPORTANT : We CAN NOT add primitives to the ArrayList. W

    have to wrap it60. into one of the wrapper classes before adding.61. */ 62.63. //get number of keys present in the ArrayList64. System.out.println("ArrayList contains " + arrayList.size() +

    elements.");65.66. /*67.68. To check whether ArrayList is empty or not, use isEmpty(

    method.69. isEmpty() returns true is ArrayList is empty, otherwise false.70.71. Finding particular value from the ArrayList:72. ArrayList's contains() method returns boolean depending upo

    the73. presence of the value in given ArrayList.74.75. Signature of the containsValue method is,76. boolean contains(Object value)77.78. */ 79.80. if( arrayList.contains(newInteger(1))){81. System.out.println("ArrayList contains 1 as value");82. }else{83. System.out.println("ArrayList does not contain 1 as value");

    84. }85.86. /*87.88. Use get method of ArrayList to get value.89.90. Signature of the get method is,91. Object get(int index)

  • 8/2/2019 Core Collections) Intervw Questns

    50/72

    92.93. */ 94.95. Integer one = (Integer) arrayList.get(0);96. System.out.println("Value at 0 index is " + one);97.98. /*99. IMPORTANT: get method returns Object, so we need t

    downcast it.100. */ 101.102. /*103.104. To search element within the ArrayList, use105. int indexOf(Object element)106.107. it returns the index of first occurrence of the specifie

    element.108.109. To find last occurrence of the specified element, use110. int lastIndexOf(Object element)111.112. */ 113.114. System.out.println("Index of first occurrence of 1 is "

    arrayList.indexOf(newInteger(1)));115.116. /*117.118. To convert ArrayList to object array, use119. Object[] toArray() method.120.121. This method returns an Object array containing all elements o

    the ArrayList122. in the correct order.123.124. */ 125.126. System.out.println("Converting ArrayList to Object array");127.128. Object[] elements = arrayList.toArray();129.130. for(int i=0; i < elements.length; i++)

  • 8/2/2019 Core Collections) Intervw Questns

    51/72

    131. System.out.println(elements[i]);132.133. /*134.135. To remove particular element from the ArrayList use,136. Object remove(int index)137.138. It returns the element that was removed from the list.139.140. To remove multiple elements from the ArrayList use,141. void removeRange(int fromIndex, int toIndex).142.143. It removes elements from the list whose index is betwee

    startIndex (inclusive)144. and toIndex(Exclusive).145.146. To remove all elements of the ArrayList use,147. void clear().148.149. It removes all elements of the ArrayList.150.151. */ 152.153. System.out.println("Is 1 removed from the ArrayList ? "

    arrayList.remove(newInteger(1)));154.

    155. }156.157. }158.159. /*160.161. OUTPUT of the above given Java ArrayList Example would be:162.163. ArrayList contains 3 key value pair.164. ArrayList contains 1 as value165. Value at 0 index is 1166. Index of first occurrence of 1 is 0167. Converting ArrayList to Object array168. 1169. 2170. 3171. Is 1 removed from the ArrayList ? true

  • 8/2/2019 Core Collections) Intervw Questns

    52/72

    172.173. */

    Java Notes: ArrayListjava.util.ArrayList allows for expandable arrays, and is basically thesame as the older the Collections Vector class. An ArrayList has thesecharacteristics:

    An ArrayList automatically expands as data is added.

    Access to any element of an ArrayList is O(1). Insertions and deletionsare O(N).

    An ArrayList has methods for inserting, deleting, and searching.

    An ArrayList can b