Sie sind auf Seite 1von 32

The Collection Framework

Java.util package

Java.util package contains a large assortment of classes and interfaces that support a board range of functionality. For example. Java.util has classes that generate random numbers, manage date and time, observe events, manipulate sets of bits, tokenize strings and handle formatted data. The java.util package also contains one of javas most powerful subsystems: The Collections Framework. The collection framework is sophisticated hierarchy of interfaces and classes that provide state-of-the-art technology for managing groups of objects. Because java.util contains a wide array of functionality, it is quite large. There are 49 classes and 16 interfaces in java.util package.

Collection Overview
The Java Collections Framework standardizes the way in which groups of objects are handled by your programs. Collections were not part of the original Java release, but were added by J2SE 1.2. Prior to the Collections Frameworks, Java provides ad hoc classes such as Dictionary, Vector, Stack and Properties to store and manipulate groups of objects. But ad hoc approach was not designed to be easily extended or adapted. Collection are an answer to this problems

The Collection Interfaces


The collection Framework defines several interfaces. Beginning with the collection interfaces is necessary because they determine the fundamental nature of the collection classes. List of interfaces:
Collection List Queue(added by J2SE 5) Set SortedSet

Collection

List

Queue

Set

SortedSet
Collection : Enables you to work with group of objects; it is at the top of the collection hierarchy. List : Extends Collection to handle sequences(list of objects). Queue : Extends Collection to handle special types of lists in which elements are removed only from the head. Set : Extends Collection to handle sets, which must contain unique elements. SortedSet : Extends Set to handle sorted sets.

Collection Interface
The Collection interface is the foundation upon which the Collections Framework is built because it must be implemented by any class that defines a collection. Collection is a generic interface. Collection declares the core methods that all collections will have. These methods can throw following Exception
UnsupportedOperationException ClassCastException

Several of these methods can throw an UnsupportedOperationException. This occurs if a collection cannot be modified. Collections that do not allow their contents to be changed are called unmodifiable. All the built-in collections are modifiable.
A ClassCastException is generated when object is incompatible with another, such as when an attempt is made to add an incompatible object to a collection.

Methods of Collection interface


public boolean add(Object) public boolean addAll(Collection) public boolean remove(Object) public boolean removeAll(Collection) public void clear() public int size() public boolean isEmpty() public boolean contains(Object) public boolean containsAll(Collection) public boolean equals(Object)

List Interface
The List interface extends Collection and declares the behavior of a collectin that stores a sequence of elements. Elements can be inserted or accessed by their position in the list, using zero-based index. A List may contain dulpicate elements. In addition to the methods defined by Collection, List defines some of its own methods.These methods will throw UnsupportedOperationException, ClassCaseException and an IndexOutOfBoundsException IndexOutOfBoundsException will raise when an invalid index is used.

Methods of List interface


public void add(int index, Object) public void addAll(int index, Collection) public int indexOf(object) public int lastIndexOf(Object) public Object get(int index) public Object set(int index, Object) public Object remove(int index) public List subList(int start, int end)

The Set interface


The Set interface defines a set. It extends Collection and declares the behaviour of a collection that does not allow duplicate elements. Therefore, the add() method returns false if an attempt is made to add duplicate elements to a set. It does not define any additional methods of its own.

The SortedSet interface


The sortedSet interface extends Set and declares the behavior of a set sorted in ascending order.in addition to those methods defined by Set, the SortedSet interface declares several methods. These methods throw following exception
NoSuchElementException ClassCastException NullPointerException NoSuchElementException is thrown when no items are contained in the invoking set. NullPointerException is thrown if an attempt is made to use a null object and a null is not allowed in the set.

Methods of SortedSet interface


Public Object first()
Public Object last() Public SortedSet headSet(Object end) Public SortedSet tailSet(Object start) Public SortedSet subSet(Object start, Object end)

The Queue interface


The Queue interface was added by J2SE 5. It extends Collection and declares the behavior of a queue, which is often a first-in, first-out list. Despite its simplicity, queue offers several points of interest. Elements can only removed from the head of the queue There are two methods that obtain and remove elements:pull() and remove(). The difference between them is that poll() returs null if the queue is empty, but remove() throw an exception. There are two methods, element() and peek(), that obtain but dont remove the elements at the head of the queue. The difference between them is that element() throws an exception if the queue is empty, but peek() returns null. Offer() only attempts to add an elements to a queue. Because some queue have a fixed length and might be full, offer() can fail.

Methods of Queue interface


public boolean offer(Object)
public Object element() public Object peek() public Object remove() public Object poll()

The Collection classes


ArrayList, LinkedList, AbstractList,AbstractSet,AbstractQue ue, priorityQueue, HashSet, TreeSet etc.

The ArrayList class


The ArrayList class extends AbstractList and implements the List interface. ArrayList supports dynamic arrays that can grow as needed. In java standard arays are of a fixed length. After arrays are created, they can not grow. An ArrayList is a variable-length array of object references. That is, an ArrayList can dynamically increase or decrease in size. ArrayList are created with an intial size. When this size is exceeded, the collection is automatically enlarged.

The LinkedList class


The LinkedList class extends AbstractSequentialList and implements the List and Queue interfaces. It provides a linked-list data structure. In addition to the moethods that it inherits, the LinkedList class defines some useful methods of its own for manipulating and accessing lists. Public void addFirst(Object) Public void addLast(Object) Public Object getFirst() Public Object getLast() Public Object removeFirst() Public Object removeLast()

The Vector class


Vector implements a dynamic array. It is similar to ArrayList, but with two differences: Vector is synchronized, and it contains many legancy methods that are not part of the Collections Framework. With the advent of collections, vector was reengineered to extends AbstractList and to implement the List interface. In addition to the collections methods defined by List, Vector defines several legacy methods.

Methods of Vector class


public void addElement(Object) public Object elementAt(int index) public Object firstElement() public Object lastElement() public int size() public int indexOf(object element) public int indexOf(Object element, int start) public int lastIndexOf(Object element) public int lastIndexOf(Object element, int start) Public boolean is Empty()

Public void setElementAt(Object element, int index) Public void insertElementAt(Object element, int index) Public boolean contains(object element) Public boolean removeElement(Object element) Public void removeElementAt(int index) public void removeAllElements() Public boolean contains(Object element) Public String toString() Public void trimTosize() Public boolean containsAll(Collection)

The Date class


The Date class encapsulates the current date and time. Its original version defined by java 1.0. When java 1.1 was released, many of the functions carried out by the original Date class were moved into the Calendar and DateFormat classes. Date supports the following constructors:
The processing of text often consist of parsing a formatted input string. Parsing is the division of text into a set of parts, or tokens. Date() Date(long) Date(int,int,int) Date(int,int,int,int,int)

Methods of Date class


Public int getDate() Public int getYear() Public int getMonth() Public int getDay() Public int getHours() Public int getMinutes(0 Public int getSeconds() Public long getTime()

Public void setDate(int) Public void setYear(int) Public void setMonth(int) Public void setHours(int) Public void setMinutes(int) Public void setSeconds(int) Public void setTime(long) Public boolean before(Date date) Public boolen after(Date date) Public boolean equals(Date date)

StringTokenizer
The StringTokenizer class provides the first step in this parsing process, often called the lexer or scanner. StringTokenizer implements Enumeration interface To use StringTokenizer, you specify an input string and a string that contains delimiters. Delimiters are characters that separate tokens. For example, ,;: sets the delimiters to a comma, semicolon and colon. The default set of delimiters consists of the whitespace characters: space, tab, newline. The StringTokenizer constructors are shown here:
StringTokenizer(String str) StringTokenizer(String str, String delimiters)

Methods of StringTokenizer class


Public int countTokens()
Public boolean hasMoreElements()

Public boolean hasMoreTokens()


Public Object nextElement()

Public String nextToken()


Public String nextToken(String delimiters)

Enumeration Interface
The Enumration interface defines the methods by which you can enumerate(obtain one at a time) the elements in a collection of objects. Enumration specifies the following two methods
public boolean hasMoreElements() public Object nextElement()

Example of Enumeration
Vector v = new Vector(); v.addElement(1); v.addElement(2); v.addElement(3); System.out.println(v); System.out.println(elements in vector :); Enumeration ev = v.elements(); While(ev.hasMoreElement()) System.out.println(ev.nextElement());

The Iterator interface


The Iterator interface defines the methods by which you can enumerate(obtain one at a time) the elements in a collection of objects. Iterator enables you to cycle through a collection, obtaining or removing elements. Iterator specifies the following three methods
public boolean hasNext() public Object next() Public void remove()

Example of Iterator with iterator()


Vector v = new Vector(); v.addElement(1); v.addElement(2); v.addElement(3); System.out.println(v); System.out.println(elements in vector :); Iterator iv = v.iterator(); While(iv.hasNext()) System.out.println(iv.next());

Set classes
HashSet class extends AbstractSet and implements the Set interface. The elements are not stored in sorted order, and the output may very. LinkedHashSet class extends HashSet.the output will be in the order in which the elements were inserted. TreeSet class extends AbstractSet and implements the Set and SortedSet interface.Objects are stored in sorted, ascending order. Access and retrieval times are quite fast, which makes TreeSet an excellent choice when storing large amount of sorted information that must be found quickly.

The Map interfaces


A map is an object that stores associations between keys and values, or key/values pairs. Given a key, you can find its value. Both keys and values are objects. The keys must be unique, but the values may be duplicated. Some maps can accept a null key and null values, others cannot. Map interface maps unique keys to values Map.entry interface describe an element in a map. This is an inner class of Map. SortedMap extends Map so that the keys are maintained in ascending order.

Das könnte Ihnen auch gefallen