Thursday, 11 December 2008

Java Collections By John Zukowski - Part5

Couple of Days i started reading Java Collections by John Zukowski.

Nice book written by John Zukowski.

Few important quotations i wanted to share from the next 2 chapters (9-10).

1) While the Set interface is the simplest of the collection types (as it doesn't add any behavior to the Collection interface), you're more likely to use the List interface and its implementations: ArrayList and LinkedList. Beyond the basic collection capabilities, the List interface adds positional access to a collection so its elements have some kind of sequential order. Thus, when retrieving elements out of a list, instead of using an Iterator to visit each element, you can fetch a ListIterator to take advantage of that positioning in order to move in both directions.

2) ArrayList Class

The ArrayList class is the Collection Framework's replacement for the Vector class. Functionally equivalent,their primary difference is that ArrayList usage is not synchronized by default, whereas Vector is. Both maintain their collection of data in an ordered fashion within an array as their backing store.

3) ArrayList shares some similarities with HashSet and TreeSet and provides some behavior that is not the same.The base implementation class is similar to HashSet and TreeSet—both extend from the AbstractCollection superclass. However, instead of further extending from AbstractSet, ArrayList extends from AbstractList. Unlike the sets, ArrayList supports storing duplicate elements.

4) Creating an ArrayList

You can use one of three constructors to create an ArrayList. For the first two constructors, an empty array list is created. The initial capacity is ten unless explicitly specified by using the second constructor. When that space becomes too small, the list will increase by approximately half.

public ArrayList()
public ArrayList (int initialCapacity)

5) Adding Single Elements

Add a single element to the list by calling the add() method:

public boolean add(Object element)
public boolean add(int index, Object element)

There are two varieties of the add() method. When called with only an element argument, the element is added to the end of the list. When add() is called with both element and index arguments, the element is added at the specific index and any elements after it are pushed forward in the list.

6) Adding Another Collection

You can add a group of elements to a list from another collection with the addAll() method:

public boolean addAll(Collection c)
public boolean addAll(int index, Collection c)

Each element in the collection passed in will be added to the current list via the equivalent of calling the add() method on each element. If an index is passed to the method call, elements are added starting at that position,moving existing elements down to fit in the new elements. Otherwise, they are added to the end. The elements are added in the order in which the collection's iterator returns them.

7) Removing Single Elements

Use the remove() method if you wish to remove a single element at a time:

public boolean remove(Object element)
public Object remove(int index)

You can remove a single element by position or by checking for equality. When passing in an element, the equals() method is used to check for equality. As List supports duplicates, the first element in the list that matches the element will be removed.

The value returned depends on which version of remove() you use. When passing in an object, remove() returns true if the object was found and removed from the list, otherwise, false is returned. For the version accepting an index argument, the object removed from the specified position is returned.

Certain removal−failure cases result in an exception being thrown. If removal is not supported, you'll get an UnsupportedOperationException thrown whether the element is present or not. If the index passed in is outside the valid range of elements, an IndexOutOfBoundsException is thrown.

8) Removing Another Collection

The third way to remove elements is with removeAll():

public boolean removeAll(Collection c)

The removeAll() method takes a Collection as an argument and removes from the list all instances of each element in the collection passed in. If an element from the passed−in collection is in the list multiple times, all instances are removed.

9) Retaining Another Collection

The retainAll() method works like removeAll() but in the opposite direction:

public boolean retainAll(Collection c)

In other words, only those elements within the collection argument are kept in the original set. Everything else is removed, instead.

10) Checking for List Containment

In addition to checking whether the list includes a specific element, you can check to see if the list contains a whole collection of other elements with the containsAll() method:

public boolean containsAll(Collection c)

This method takes a Collection as its argument and reports if the elements of the passed−in collection are a subset of the current list. In other words, is each element of the collection also an element of the list? The current list can contain other elements but the passed−in collection cannot or containsAll() will return false. If an element is in the passed−in collection multiple times, it only needs to be in the source list once to be successful.

11) Replacing Elements

You can replace elements in a list with the set() method:

public Object set(int index, Object element)

Use the set() method when you need to replace the element at a specific position in the list. The object being replaced is returned by the set() method. If the index happens to be invalid, an IndexOutOfBoundsException is thrown.

12) Checking Size

To find out how many elements are in a list, use its size() method:

public int size()

ArrayList also has an isEmpty() method to get the size and to check to see if no elements are in the list:

public boolean isEmpty()

13) Checking for Equality

The ArrayList class gets its equals() method from the AbstractList class:

public boolean equals(Object o)

An ArrayList is equal to another object if the other object implements the List interface, has the same size(),
and contains the same elements in the same positions.

The equals() method of the elements is used to check if two elements at the same position are equivalent.

14) HashMap Class

The HashMap is the most commonly used implementation of the Map interface. It provides a basic key−value map where the elements are unordered.

15) Removing Key−Value Pairs

When you need to remove an element from a hash map, call the remove() method with the key as its argument:

public Object remove(Object key)

If the key is present as a key within the hash table, the key−value pair will be removed and the value object will be returned. If the object is not present in the map, null will be returned.

16) Cloning Hash Map

The HashMap class provides its own implementation of the clone() method:

public Object clone()

This functions similarly to passing the hash map to the copy constructor of a HashMap or to creating an empty HashMap and calling putAll().

17) Creating a WeakHashMap

The four constructors of WeakHashMap are the same as HashMap:

public WeakHashMap()
public WeakHashMap(int initialCapacity)
public WeakHashMap(int initialCapacity, float loadFactor)
public WeakHashMap(Map map)

The final copy constructor was missing from the Java 1.2 release and was added with the 1.3 release. To fully understand the use of WeakHashMap, it is necessary to understand the different types of Reference objects that Java supports.

18) Creating a TreeMap

There are four constructors for TreeMap. The basic two are present: one, the no argument version, creates an empty list, and the other, the standard copy constructor.

public TreeMap()
public TreeMap(Map map)

Sorted maps require two additional constructors; one accepts a Comparator to define a custom sort order, and the other accepts a SortedMap for an optimized copy constructor:

public TreeMap(Comparator comp)
public TreeMap(SortedMap map)

Elements in a TreeMap are sorted by their natural ordering—they must implement Comparable—unless a Comparator is provided. If a SortedMap is provided, the new TreeMap retains its Comparator.

About the Author

John Zukowski has been involved with the Java platform since it was just called Java, 11 years and running, since 1995. He is actively working with SavaJe Technologies to finish up the JavaOne 2006 device of show: the Jasper S20 mobile phone. He currently writes a monthly column for Sun’s Core Java Technologies Tech Tips and Technology Fundamentals Newsletter. He has contributed content to numerous other sites, including jGuru, DevX, Intel, and JavaWorld. He has written many other popular titles on Java, including Java AWT Reference (O’Reilly), Mastering Java 2 (Sybex), Borlands’ JBuilder: No Experience Required (Sybex), Learn Java with JBuilder 6 (Apress), Java Collections (Apress), and The Definitive Guide to Swing (Apress).

No comments: