Saturday 3 August 2013

34:Collections and Util package

Learning Objectives
After completing this session, you will be able to describe the following:
‰  Define collections
‰  Describe the importance of collections
‰  Identify Core Collection Interfaces
‰  List the implementations
Collection
‰  A “collection” object sometimes called a container is simply an object that groups
multiple elements into a single unit.
‰  Collections are used to store, retrieve, manipulate, and communicate aggregate data.
Typically, they represent data items that forma natural group, such as a poker hand (a
collection of cards), a mail folder (a collection of letters), or a telephone directory (a
mapping of names to phone numbers).
Collection Framework
A collections framework is a unified architecturefor representing and manipulating collections.
All collections frameworks contain the following:
‰  Interfaces
‰  Implementations
‰  Algorithms
Benefits of Collection Framework
The benefits of collection framework are:
‰  Reduces programming effort
‰  Increases program speed and quality
‰  Allows interoperability among unrelated APIs: The collection interfaces are the
vernacular by which APIs pass collections back and forth
‰  Reduce effort to learn and use new APIs
‰  Reduces effort to design new APIs
‰  Fosters software reuse: New data structuresthat conform to the standard collection
interfaces are by nature reusable
Collection Interfaces
‰  Collection interfaces are abstract data types that represent collections. Collection
interfaces are in the form of Java interfaces.
‰  Interfaces allow collections to be manipulated independently of the implementation
details of their representation, which is called the polymorphic behavior.
‰  In Java programming language (and other object-oriented languages), interfaces
generally form a hierarchy. You chooseone that meets your need as a type.
Implementations
‰  Implementations are the data objects used to store collections, which implement the
interfaces.
‰  Each of the implementations for general purpose (you will see in the following slide)
provide all optional operations contained in its interface.
‰  Java Collections Framework also provides several implementations for special
purpose situations that require nonstandard performance, usage restrictions, or other
unusual behavior.
Types of Implementations
The types of implementations are:
‰  General-purpose implementations
‰  Special-purpose implementations
‰  Concurrent implementations
‰  Wrapper implementations
‰  Convenience implementations
‰  Abstract implementations
General Purpose Implementations












Algorithms
‰  These are the methods that perform useful computations, such as searching and
sorting, on objects, which implement collection interfaces.
‰  The algorithms are said to be polymorphic that is, the same method can be used on
many different implementations of the appropriate collection interface. In essence,
algorithms are reusable functionality.
Core Collection Interfaces Hierarchy
The hierarchy of Core Collection Interfaces are shown in the following figure:















Core Collection Interfaces
‰  Core Collection Interfaces are the foundation of the Java Collections Framework.
‰  Core Collection Interfaces form an inheritance hierarchy among themselves.
‰  You can create a new collection interface from them (highly likely you do not have to).
“Collection” Interface
‰  Collection interface is the rootof the collection hierarchy.
‰  Collection interface is the least common denominator that all collections implement.
Every collection object is a type of Collection interface.
‰  Collection interface is used to pass collection objects around and to manipulate them
when maximum generality is desired. Apply Collection interface as a type.
‰  JDK (Java Development Kit) does not provide any direct implementations of this
interface but provides implementations of more specific sub interfaces, such as Set
and List.
“Collection” Interface (Java SE 5)
public interface Collection<E> extends Iterable<E> {
// Basic operations
int size();
boolean isEmpty();
boolean contains(Object element);
boolean add(E element); //optional
boolean remove(Object element); //optional
Iterator<E> iterator();
// Bulk operations
boolean containsAll(Collection<?> c);
boolean addAll(Collection<? extends E> c); //optional
boolean removeAll(Collection<?> c); //optional
boolean retainAll(Collection<?> c); //optional
void clear(); //optional
// Array operations
Object[] toArray();
<T> T[] toArray(T[] a);
}
Example: Usage “Collection” Interface as a Type
// Create a ArrayList collection object instance and assign it
// to Collection type.
Collection c1 = new ArrayList();
// Use methods of Collection interface.
//
// Polymorphic behavior is expected. For example,
// the add() implementation of ArrayList class will be
// invoked. For example, depending on the implementation,
// duplication is allowed or not allowed.
boolean b1 = c1.isEmpty();
boolean b2 = c1.add(new Integer(1))
add() and remove() Methods of Collection Interface
‰  The add() method is defined generally enough so that it makes sense for collections,
which allow duplicates as well as those that do not.
‰  It guarantees that the Collection will contain the specified element after the call
completes, and returns true if the Collection changes as a result of the call. add()
method of Set interface follows “no duplicate” rule.
Bulk Operations
The various bulk operations are:
‰  containsAll() returns true if the target Collection contains all of the elements in the
specified Collection.
‰  addAll() adds all of the elements in the specified Collection to the target Collection.
‰  removeAll() removes from the target Collection all of its elements that are also
contained in the specified Collection.
‰  retainAll() removes from the target Collection all its elements that are not also
contained in the specified Collection. It retains only those elements in the target
Collection that are also contained in the specified Collection.
‰  clear() removes all elements from the Collection.
Example: removeAll()
‰  removeAll() removes all instances of a specified element, e, from a Collection, c:
c.removeAll(Collections.singleton(e));
‰  removeAll() removes all of the null elements from a Collection:
c.removeAll(Collections.singleton(null));
‰  Collections.singleton() , which is a static factory method returns an immutable Set
containing only the specified element.
Array Operations
‰  The toArray() method is provided as a bridge between collections and older APIs that
expect arrays on input.
‰  The array operations allow the contents of a Collection to be translated into an array.
Example: Array Operations
The simple form with no arguments creates a new array of Object.
Object[] a = c.toArray();
Suppose c is known to contain only strings. The following snippet dumps the contents of c into a
newly allocated array of String whose length is identical to the number of elements in c.
String[] a = c.toArray();
Try It Out
Problem Statement:
Write a program that illustrates the usage of ArrayList class, which is implemented from the List
interface.
Code:
import java.util.*;
public class TestArrayList {
public static void main(String[] args) {
List<String> test = new ArrayList<String>();
String str = "hi";
test.add("string");
test.add(str);
test.add(str + str);
System.out.println(test.size());
System.out.println(test.contains(42));
System.out.println(test.contains("hihi"));
test.remove("hi");
System.out.println(test.size());
}
}


Tips and Tricks:
List out key points on String Buffers.
Solution:
‰  String Buffers are mutable strings.
‰  StringBuffer is a final class.
‰  They can be created empty, from a string orwith a capacity. An empty StringBuffer is
created with 16-character capacity. A StringBuffer created from a String has the
capacity of the length of String + 16. StringBuffer created with the specified capacity
has the exact capacity specified. As they can grow dynamically in size without bounds,
capacity does not have much effect.
‰  append, insert, setCharAt, and reverse are used to manipulate the string buffer.
‰  setLength changes the length. If the current content is larger than specified length,
then it is truncated. If it is smaller than the specified length, then nulls are padded. This
method does not affect the capacity.
‰  equals on StringBuffer does a shallow comparison (same like ==) and will return true
only if the objects are same. Do not use it to test content equality.
‰  trim is not a StringBuffer method.
‰  There is no relationship between String and StringBuffer. Both extend Object class.
‰  String context means, ‘+’ operator appearing with one String operand. String
concatenation cannot be applied to StringBuffer.
‰  A new StringBuffer is created.
‰  All operands are appended by calling toString method, if needed.
‰  Finally a string is returned by calling toString on the StringBuffer.

Summary
‰  Common collection activities include adding objects, removing objects, verifying object
inclusion, retrieving objects, and iterating.
‰  Three meanings for “collection”:
oCollection: Represents the data structure in which objects are stored
oCollection: java.utilinterface from which Set and List extend
oCollections: A class that holds static collection utility methods
‰  Four basic sub-flavors of collections: Sorted, Unsorted, Ordered, Unordered
oOrdered: Iterating through a collection in a specific, non-random order.
oSorted: Iterating through a collection in a sorted order.
‰  Sorting can be alphabetic, numeric, or programmer-defined.
Test Your Understanding
1.State true or false for the following:
a)The Collection interface helps you to workwith collection of objects. This interface
is at the top of the collections hierarchy.The collections framework is built on this
interface.
b)Certain static methods, which operate on collections, are defined in the
Collections class. Such methods are known as algorithms.



No comments:

Post a Comment