the collection framework by kamalakar dandu
TRANSCRIPT
-
8/2/2019 The Collection Framework by Kamalakar Dandu
1/32
The Collection Framework
Java.util package
-
8/2/2019 The Collection Framework by Kamalakar Dandu
2/32
Java.util package contains a large assortment ofclasses and interfaces that support a board range offunctionality. For example. Java.util has classes
that generate random numbers, manage date andtime, 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 CollectionsFramework. The collection framework issophisticated hierarchy of interfaces and classesthat 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 classesand 16 interfaces in java.util package.
-
8/2/2019 The Collection Framework by Kamalakar Dandu
3/32
Collection Overview
The Java Collections Framework standardizes theway in which groups of objects are handled byyour programs. Collections were not part of theoriginal Java release, but were added by J2SE 1.2.Prior to the Collections Frameworks, Javaprovides ad hoc classes such as Dictionary,Vector, Stack and Properties to store and
manipulate groups of objects. But ad hoc approachwas not designed to be easily extended or adapted.Collection are an answer to this problems
-
8/2/2019 The Collection Framework by Kamalakar Dandu
4/32
The Collection Interfaces
The collection Framework defines severalinterfaces. Beginning with the collection interfacesis necessary because they determine thefundamental nature of the collection classes.
List of interfaces:
Collection
List Queue(added by J2SE 5)
Set
SortedSet
-
8/2/2019 The Collection Framework by Kamalakar Dandu
5/32
Set
Collection
List Queue
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 whichelements are removed only from the head.
Set : Extends Collection to handle sets, which must contain unique
elements.
SortedSet : Extends Set to handle sorted sets.
-
8/2/2019 The Collection Framework by Kamalakar Dandu
6/32
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 acollection. Collection is a generic interface.
Collection declares the core methods that all
collections will have. These methods can throw
following Exception UnsupportedOperationException
ClassCastException
-
8/2/2019 The Collection Framework by Kamalakar Dandu
7/32
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 collectionsare modifiable.
A ClassCastException is generated when object
is incompatible with another, such as when anattempt is made to add an incompatible object
to a collection.
-
8/2/2019 The Collection Framework by Kamalakar Dandu
8/32
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)
-
8/2/2019 The Collection Framework by Kamalakar Dandu
9/32
List Interface
The List interface extends Collection and declares
the behavior of a collectin that stores a sequence ofelements. Elements can be inserted or accessed bytheir position in the list, using zero-based index. AList may contain dulpicate elements.
In addition to the methods defined by Collection,List defines some of its own methods.Thesemethods will throwUnsupportedOperationException,
ClassCaseException and anIndexOutOfBoundsException
IndexOutOfBoundsException will raise when aninvalid index is used.
-
8/2/2019 The Collection Framework by Kamalakar Dandu
10/32
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)
-
8/2/2019 The Collection Framework by Kamalakar Dandu
11/32
The Set interface
The Set interface defines a set. It extends
Collection and declares the behaviour of a
collection that does not allow duplicateelements. Therefore, the add() method
returns false if an attempt is made to add
duplicate elements to a set. It does notdefine any additional methods of its own.
-
8/2/2019 The Collection Framework by Kamalakar Dandu
12/32
The SortedSet interface
The sortedSet interface extends Set and declaresthe behavior of a set sorted in ascending order.inaddition to those methods defined by Set, theSortedSet interface declares several methods.
These methods throw following exception NoSuchElementException
ClassCastException
NullPointerException
NoSuchElementException is thrown when no items arecontained 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.
-
8/2/2019 The Collection Framework by Kamalakar Dandu
13/32
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)
-
8/2/2019 The Collection Framework by Kamalakar Dandu
14/32
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 themis that poll() returs null if the queue is empty, but remove()throw an exception.
There are two methods, element() and peek(), that obtain butdont remove the elements at the head of the queue. The
difference between them is that element() throws anexception if the queue is empty, but peek() returns null.
Offer() only attempts to add an elements to a queue. Becausesome queue have a fixed length and might be full, offer() canfail.
-
8/2/2019 The Collection Framework by Kamalakar Dandu
15/32
Methods of Queue interface
public boolean offer(Object)
public Object element()
public Object peek()
public Object remove()
public Object poll()
-
8/2/2019 The Collection Framework by Kamalakar Dandu
16/32
The Collection classes
ArrayList, LinkedList,AbstractList,AbstractSet,AbstractQue
ue, priorityQueue, HashSet, TreeSet
etc.
-
8/2/2019 The Collection Framework by Kamalakar Dandu
17/32
The ArrayList class
The ArrayList class extends AbstractList andimplements the List interface.
ArrayList supports dynamic arrays that can growas needed. In java standard arays are of a fixedlength. After arrays are created, they can not grow.An ArrayList is a variable-length array of objectreferences. That is, an ArrayList can dynamicallyincrease or decrease in size.
ArrayList are created with an intial size. Whenthis size is exceeded, the collection isautomatically enlarged.
-
8/2/2019 The Collection Framework by Kamalakar Dandu
18/32
The LinkedList class
The LinkedList class extends AbstractSequentialList and
implements the List and Queue interfaces. It provides alinked-list data structure.
In addition to the moethods that it inherits, the LinkedListclass defines some useful methods of its own formanipulating and accessing lists.
Public void addFirst(Object)
Public void addLast(Object)
Public Object getFirst()
Public Object getLast()
Public Object removeFirst()
Public Object removeLast()
-
8/2/2019 The Collection Framework by Kamalakar Dandu
19/32
The Vector class
Vector implements a dynamic array. It is similarto ArrayList, but with two differences: Vector issynchronized, and it contains many legancymethods that are not part of the CollectionsFramework.
With the advent of collections, vector wasreengineered to extends AbstractList and toimplement the List interface.
In addition to the collections methods defined byList, Vector defines several legacy methods.
-
8/2/2019 The Collection Framework by Kamalakar Dandu
20/32
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()
-
8/2/2019 The Collection Framework by Kamalakar Dandu
21/32
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)
-
8/2/2019 The Collection Framework by Kamalakar Dandu
22/32
The Date class
The Date class encapsulates the current date andtime. Its original version defined by java 1.0.When java 1.1 was released, many of the functionscarried 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 formattedinput 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)
-
8/2/2019 The Collection Framework by Kamalakar Dandu
23/32
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()
-
8/2/2019 The Collection Framework by Kamalakar Dandu
24/32
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)
-
8/2/2019 The Collection Framework by Kamalakar Dandu
25/32
StringTokenizer
The StringTokenizer class provides the first step in thisparsing process, often called the lexer or scanner.
StringTokenizer implements Enumeration interface
To use StringTokenizer, you specify an input string and astring 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 whitespacecharacters: space, tab, newline.
The StringTokenizer constructors are shown here: StringTokenizer(String str)
StringTokenizer(String str, String delimiters)
-
8/2/2019 The Collection Framework by Kamalakar Dandu
26/32
Methods of StringTokenizer class
Public int countTokens()
Public boolean hasMoreElements()
Public boolean hasMoreTokens()
Public Object nextElement()
Public String nextToken()
Public String nextToken(String delimiters)
-
8/2/2019 The Collection Framework by Kamalakar Dandu
27/32
Enumeration Interface
The Enumration interface defines themethods by which you can
enumerate(obtain one at a time) theelements in a collection of objects.
Enumration specifies the following twomethods
public boolean hasMoreElements()
public Object nextElement()
-
8/2/2019 The Collection Framework by Kamalakar Dandu
28/32
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());
-
8/2/2019 The Collection Framework by Kamalakar Dandu
29/32
The Iterator interface
The Iterator interface defines the methods bywhich you can enumerate(obtain one at a time) theelements 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()
-
8/2/2019 The Collection Framework by Kamalakar Dandu
30/32
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());
-
8/2/2019 The Collection Framework by Kamalakar Dandu
31/32
Set classes HashSet classextends AbstractSet and
implements the Set interface. The elements are notstored in sorted order, and the output may very.
LinkedHashSet classextends HashSet.the outputwill be in the order in which the elements were
inserted. TreeSet classextends AbstractSet and
implements the Set and SortedSetinterface.Objects are stored in sorted, ascending
order. Access and retrieval times are quite fast,which makes TreeSet an excellent choice whenstoring large amount of sorted information thatmust be found quickly.
-
8/2/2019 The Collection Framework by Kamalakar Dandu
32/32
The Map interfaces
A map is an object that stores associationsbetween 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, butthe values may be duplicated. Some maps canaccept a null key and null values, others cannot.
Map interfacemaps unique keys to values
Map.entry interfacedescribe an element in amap. This is an inner class of Map.
SortedMapextends Map so that the keys are
maintained in ascending order