Java Basics Unit 5

Download as pdf or txt
Download as pdf or txt
You are on page 1of 41

The Collection Interfaces

The collections framework defines several interfaces.


Sr.No. Interface & Description

1 The Collection Interface

This enables you to work with groups of objects; it is at the top of the
collections hierarchy.
2 The List Interface
This extends Collection and an instance of List stores an ordered
collection of elements.
3 The Set
This extends Collection to handle sets, which must contain unique
elements.
4 The SortedSet
This extends Set to handle sorted sets.
5 The Map
This maps unique keys to values.
6 The Map.Entry
This describes an element (a key/value pair) in a map. This is an inner
class of Map.
7 The SortedMap
This extends Map so that the keys are maintained in an ascending order.
8 The Enumeration
This is legacy interface defines the methods by which you can enumerate
(obtain one at a time) the elements in a collection of objects. This legacy
interface has been superceded by Iterator.

The Collection Classes


Java provides a set of standard collection classes that implement Collection
interfaces. Some of the classes provide full implementations that can be used as-is
and others are abstract class, providing skeletal implementations that are used as
starting points for creating concrete collections.
The standard collection classes are summarized in the following table −
Sr.No. Class & Description

1 AbstractCollection
Implements most of the Collection interface.
2 AbstractList
Extends AbstractCollection and implements most of the List interface.
3 AbstractSequentialList
Extends AbstractList for use by a collection that uses sequential rather than
random access of its elements.
4 LinkedList
Implements a linked list by extending AbstractSequentialList.
5 ArrayList
Implements a dynamic array by extending AbstractList.
6 AbstractSet
Extends AbstractCollection and implements most of the Set interface.
7 HashSet
Extends AbstractSet for use with a hash table.
8 LinkedHashSet
Extends HashSet to allow insertion-order iterations.
9 TreeSet
Implements a set stored in a tree. Extends AbstractSet.
10 AbstractMap
Implements most of the Map interface.
11 HashMap
Extends AbstractMap to use a hash table.
12 TreeMap
Extends AbstractMap to use a tree.
13 WeakHashMap
Extends AbstractMap to use a hash table with weak keys.
14 LinkedHashMap
Extends HashMap to allow insertion-order iterations.
15 IdentityHashMap
Extends AbstractMap and uses reference equality when comparing
documents.

• The AbstractCollection, AbstractSet, AbstractList,


AbstractSequentialList and AbstractMap classes provide skeletal
implementations of the core collection interfaces, to minimize the effort
required to implement them.

Sr.No. Class & Description

1 Vector

This implements a dynamic array. It is similar to ArrayList, but with some


differences.
2 Stack
Stack is a subclass of Vector that implements a standard last-in, first-out
stack.
3 Dictionary
Dictionary is an abstract class that represents a key/value storage
repository and operates much like Map.
4 Hashtable
Hashtable was part of the original java.util and is a concrete
implementation of a Dictionary.
5 Properties
Properties is a subclass of Hashtable. It is used to maintain lists of values
in which the key is a String and the value is also a String.
6 BitSet
A BitSet class creates a special type of array that holds bit values. This
array can increase in size as needed.
Java - The List Interface

The List interface extends Collection and declares the behavior of a collection that
stores a sequence of elements.
• Elements can be inserted or accessed by their position in the list, using a
zero-based index.
• A list may contain duplicate elements.
• In addition to the methods defined by Collection, List defines some of its
own, which are summarized in the following table.
• Several of the list methods will throw an UnsupportedOperationException if
the collection cannot be modified, and a ClassCastException is generated
when one object is incompatible with another.
Sr.No. Method & Description

1
void add(int index, Object obj)
Inserts obj into the invoking list at the index passed in the index. Any pre-
existing elements at or beyond the point of insertion are shifted up. Thus,
no elements are overwritten.
2
boolean addAll(int index, Collection c)
Inserts all elements of c into the invoking list at the index passed in the
index. Any pre-existing elements at or beyond the point of insertion are
shifted up. Thus, no elements are overwritten. Returns true if the invoking
list changes and returns false otherwise.
3
Object get(int index)
Returns the object stored at the specified index within the invoking
collection.
4
int indexOf(Object obj)
Returns the index of the first instance of obj in the invoking list. If obj is not
an element of the list, .1 is returned.
5
int lastIndexOf(Object obj)
Returns the index of the last instance of obj in the invoking list. If obj is not
an element of the list, .1 is returned.
6
ListIterator listIterator( )
Returns an iterator to the start of the invoking list.
7
ListIterator listIterator(int index)
Returns an iterator to the invoking list that begins at the specified index.
8
Object remove(int index)
Removes the element at position index from the invoking list and returns
the deleted element. The resulting list is compacted. That is, the indexes of
subsequent elements are decremented by one.
9
Object set(int index, Object obj)
Assigns obj to the location specified by index within the invoking list.
10
List subList(int start, int end)
Returns a list that includes elements from start to end.1 in the invoking list.
Elements in the returned list are also referenced by the invoking object.

Example
The above interface has been implemented in various classes like ArrayList or
LinkedList, etc.
Following is the example to explain few methods from various class implementation
of the above collection methods –

importjava.util.*;
publicclassCollectionsDemo{

publicstaticvoidmain(String[]args){
List a1 =newArrayList();
a1.add("Zara");
a1.add("Mahnaz");
a1.add("Ayan");
System.out.println(" ArrayList Elements");
System.out.print("\t"+ a1);

List l1 =newLinkedList();
l1.add("Zara");
l1.add("Mahnaz");
l1.add("Ayan");
System.out.println();
System.out.println(" LinkedList Elements");
System.out.print("\t"+ l1);
}
}

This will produce the following result −

Output
ArrayList Elements
[Zara, Mahnaz, Ayan]
LinkedList Elements
[Zara, Mahnaz, Ayan]
Java - The Enumeration Interface

The Enumeration interface defines the methods by which you can enumerate
(obtain one at a time) the elements in a collection of objects.
The methods declared by Enumeration are summarized in the following table −
Sr.No. Method & Description

1
boolean hasMoreElements( )
When implemented, it must return true while there are still more elements to
extract, and false when all the elements have been enumerated.
2
Object nextElement( )
This returns the next object in the enumeration as a generic Object
reference.

Example
Following is an example showing usage of Enumeration.
importjava.util.Vector;
importjava.util.Enumeration;

publicclassEnumerationTester{

publicstaticvoidmain(Stringargs[]){
Enumeration days;
VectordayNames=newVector();

dayNames.add("Sunday");
dayNames.add("Monday");
dayNames.add("Tuesday");
dayNames.add("Wednesday");
dayNames.add("Thursday");
dayNames.add("Friday");
dayNames.add("Saturday");
days =dayNames.elements();

while(days.hasMoreElements()){
System.out.println(days.nextElement());
}
}
}

This will produce the following result −

Output
Sunday
Monday
Tuesday
Wednesday
Thursday
Friday
Saturday
Java - The ArrayList Class
• The ArrayList class extends AbstractList and implements the List interface.
ArrayList supports dynamic arrays that can grow as needed.
• Standard Java arrays are of a fixed length.
Following is the list of the constructors provided by the ArrayList class.
Sr.No. Constructor & Description

1
ArrayList( )
This constructor builds an empty array list.
2
ArrayList(Collection c)
This constructor builds an array list that is initialized with the elements of the
collection c.
3
ArrayList(int capacity)
This constructor builds an array list that has the specified initial capacity.
The capacity is the size of the underlying array that is used to store the
elements. The capacity grows automatically as elements are added to an
array list.

Apart from the methods inherited from its parent classes, ArrayList defines the
following methods −
Sr.No. Method & Description

1
void add(int index, Object element)
Inserts the specified element at the specified position index in this list.
Throws IndexOutOfBoundsException if the specified index is out of range
(index < 0 || index >size()).
2
boolean add(Object o)
Appends the specified element to the end of this list.
3
boolean addAll(Collection c)
Appends all of the elements in the specified collection to the end of this list,
in the order that they are returned by the specified collection's iterator.
Throws NullPointerException, if the specified collection is null.
4
boolean addAll(int index, Collection c)
Inserts all of the elements in the specified collection into this list, starting at
the specified position. Throws NullPointerException if the specified
collection is null.
5
void clear()
Removes all of the elements from this list.
6
Object clone()
Returns a shallow copy of this ArrayList.
7
boolean contains(Object o)
Returns true if this list contains the specified element. More formally, returns
true if and only if this list contains at least one element e such that (o==null
? e==null : o.equals(e)).
8
void ensureCapacity(int minCapacity)
Increases the capacity of this ArrayList instance, if necessary, to ensure that
it can hold at least the number of elements specified by the minimum
capacity argument.
9
Object get(int index)
Returns the element at the specified position in this list. Throws
IndexOutOfBoundsException if the specified index is out of range (index < 0
|| index >= size()).
10
int indexOf(Object o)
Returns the index in this list of the first occurrence of the specified element,
or -1 if the List does not contain this element.
11
int lastIndexOf(Object o)
Returns the index in this list of the last occurrence of the specified element,
or -1 if the list does not contain this element.
12
Object remove(int index)
Removes the element at the specified position in this list. Throws
IndexOutOfBoundsException if the index out is of range (index < 0 || index
>= size()).
13
protected void removeRange(int fromIndex, int toIndex)
Removes from this List all of the elements whose index is between
fromIndex, inclusive and toIndex, exclusive.
14
Object set(int index, Object element)
Replaces the element at the specified position in this list with the specified
element. Throws IndexOutOfBoundsException if the specified index is out of
range (index < 0 || index >= size()).
15
int size()
Returns the number of elements in this list.
16
Object[] toArray()
Returns an array containing all of the elements in this list in the correct
order. Throws NullPointerException if the specified array is null.
17
Object[] toArray(Object[] a)
Returns an array containing all of the elements in this list in the correct
order; the runtime type of the returned array is that of the specified array.
18
void trimToSize()
Trims the capacity of this ArrayList instance to be the list's current size.

Example
The following program illustrates several of the methods supported by ArrayList −

importjava.util.*;
public class ArrayListDemo{

public static void main(String args[]){


// create an array list
ArrayList al =new ArrayList();
System.out.println("Initial size of al: "+al.size());

// add elements to the array list


al.add("C");
al.add("A");
al.add("E");
al.add("B");
al.add("D");
al.add("F");
al.add(1,"A2");
System.out.println("Size of al after additions: "+al.size());

// display the array list


System.out.println("Contents of al: "+ al);

// Remove elements from the array list


al.remove("F");
al.remove(2);
System.out.println("Size of al after deletions: "+al.size());
System.out.println("Contents of al: "+ al);
}
}
This will produce the following result −

Output
Initial size of al: 0
Size of al after additions: 7
Contents of al: [C, A2, A, E, B, D, F]
Size of al after deletions: 5
Contents of al: [C, A2, E, B, D]
Java - The LinkedList Class

• The LinkedList class extends AbstractSequentialList and implements the List


interface.
• It provides a linked-list data structure.
• Following are the constructors supported by the LinkedList class.
Sr.No. Constructor & Description

1
LinkedList( )
This constructor builds an empty linked list.
2
LinkedList(Collection c)
This constructor builds a linked list that is initialized with the elements of the
collection c.

Apart from the methods inherited from its parent classes, LinkedList defines
following methods −

Sr.No. Method & Description

1
void add(int index, Object element)
Inserts the specified element at the specified position index in this list.
Throws IndexOutOfBoundsException if the specified index is out of range
(index < 0 || index >size()).

2
boolean add(Object o)
Appends the specified element to the end of this list.

3
boolean addAll(Collection c)
Appends all of the elements in the specified collection to the end of this list,
in the order that they are returned by the specified collection's iterator.
Throws NullPointerException if the specified collection is null.

4
boolean addAll(int index, Collection c)
Inserts all of the elements in the specified collection into this list, starting at
the specified position. Throws NullPointerException if the specified
collection is null.
5
void addFirst(Object o)
Inserts the given element at the beginning of this list.

6
void addLast(Object o)
Appends the given element to the end of this list.

7
void clear()
Removes all of the elements from this list.

8
Object clone()
Returns a shallow copy of this LinkedList.

9
boolean contains(Object o)
Returns true if this list contains the specified element. More formally,
returns true if and only if this list contains at least one element e such that
(o==null ? e==null : o.equals(e)).

10
Object get(int index)
Returns the element at the specified position in this list. Throws
IndexOutOfBoundsException if the specified index is out of range (index <
0 || index >= size()).

11
Object getFirst()
Returns the first element in this list. Throws NoSuchElementException if
this list is empty.

12
Object getLast()
Returns the last element in this list. Throws NoSuchElementException if
this list is empty.

13
int indexOf(Object o)
Returns the index in this list of the first occurrence of the specified element,
or -1 if the list does not contain this element.

14
int lastIndexOf(Object o)
Returns the index in this list of the last occurrence of the specified element,
or -1 if the list does not contain this element.

15
ListIteratorlistIterator(int index)
Returns a list-iterator of the elements in this list (in proper sequence),
starting at the specified position in the list. Throws
IndexOutOfBoundsException if the specified index is out of range (index <
0 || index >= size()).

16
Object remove(int index)
Removes the element at the specified position in this list. Throws
NoSuchElementException if this list is empty.

17
boolean remove(Object o)
Removes the first occurrence of the specified element in this list. Throws
NoSuchElementException if this list is empty. Throws
IndexOutOfBoundsException if the specified index is out of range (index <
0 || index >= size()).

18
Object removeFirst()
Removes and returns the first element from this list. Throws
NoSuchElementException if this list is empty.

19
Object removeLast()
Removes and returns the last element from this list. Throws
NoSuchElementException if this list is empty.

20
Object set(int index, Object element)
Replaces the element at the specified position in this list with the specified
element. Throws IndexOutOfBoundsException if the specified index is out
of range (index < 0 || index >= size()).

21
int size()
Returns the number of elements in this list.

22
Object[] toArray()
Returns an array containing all of the elements in this list in the correct
order. Throws NullPointerException if the specified array is null.
23
Object[] toArray(Object[] a)
Returns an array containing all of the elements in this list in the correct
order; the runtime type of the returned array is that of the specified array.

Example
The following program illustrates several of the methods supported by LinkedList −
Import java.util.*;
Public class LinkedListDemo{

Public static void main(String args[]){


// create a linked list
LinkedListll=new LinkedList();

// add elements to the linked list


ll.add("F");
ll.add("B");
ll.add("D");
ll.add("E");
ll.add("C");
ll.addLast("Z");
ll.addFirst("A");
ll.add(1,"A2");
System.out.println("Original contents of ll: "+ll);

// remove elements from the linked list


ll.remove("F");
ll.remove(2);
System.out.println("Contents of ll after deletion: "+ll);

// remove first and last elements


ll.removeFirst();
ll.removeLast();
System.out.println("ll after deleting first and last: "+ll);

// get and set a value


Objectval=ll.get(2);
ll.set(2,(String)val+" Changed");
System.out.println("ll after change: "+ll);
}
}

This will produce the following result −

Output
Original contents of ll: [A, A2, F, B, D, E, C, Z]
Contents of ll after deletion: [A, A2, D, E, C, Z]
ll after deleting first and last: [A2, D, E, C]
ll after change: [A2, D, E Changed, C]
Java - The Vector Class

Vector implements a dynamic array.


It is similar to ArrayList, but with two differences −
• Vector is synchronized.
• Vector contains many legacy methods that are not part of the collections
framework.
Vector proves to be very useful if you don't know the size of the array in advance or
you just need one that can change sizes over the lifetime of a program.
Following is the list of constructors provided by the vector class.

Sr.No. Constructor & Description

1
Vector( )
This constructor creates a default vector, which has an initial size of 10.

2
Vector(int size)
This constructor accepts an argument that equals to the required size, and
creates a vector whose initial capacity is specified by size.

3
Vector(int size, int incr)
This constructor creates a vector whose initial capacity is specified by size
and whose increment is specified by incr. The increment specifies the
number of elements to allocate each time that a vector is resized upward.

4
Vector(Collection c)
This constructor creates a vector that contains the elements of collection c.

Apart from the methods inherited from its parent classes, Vector defines the
following methods −

Sr.No. Method & Description

1
void add(int index, Object element)
Inserts the specified element at the specified position in this Vector.
2
boolean add(Object o)
Appends the specified element to the end of this Vector.

3
Boolean addAll(Collection c)
Appends all of the elements in the specified Collection to the end of this
Vector, in the order that they are returned by the specified Collection's
Iterator.

4
Boolean addAll(int index, Collection c)
Inserts all of the elements in in the specified Collection into this Vector at
the specified position.

5
void addElement(Object obj)
Adds the specified component to the end of this vector, increasing its size
by one.

6
int capacity()
Returns the current capacity of this vector.

7
void clear()
Removes all of the elements from this vector.

8
Object clone()
Returns a clone of this vector.

9
boolean contains(Object elem)
Tests if the specified object is a component in this vector.

10
booleancontainsAll(Collection c)
Returns true if this vector contains all of the elements in the specified
Collection.

11
void copyInto(Object[] anArray)
Copies the components of this vector into the specified array.
12
Object elementAt(int index)
Returns the component at the specified index.

13
Enumeration elements()
Returns an enumeration of the components of this vector.

14
void ensureCapacity(int minCapacity)
Increases the capacity of this vector, if necessary, to ensure that it can hold
at least the number of components specified by the minimum capacity
argument.

15
boolean equals(Object o)
Compares the specified Object with this vector for equality.

16
Object firstElement()
Returns the first component (the item at index 0) of this vector.

17
Object get(int index)
Returns the element at the specified position in this vector.

18
int hashCode()
Returns the hash code value for this vector.

19
int indexOf(Object elem)
Searches for the first occurence of the given argument, testing for equality
using the equals method.

20
int indexOf(Object elem, int index)
Searches for the first occurence of the given argument, beginning the
search at index, and testing for equality using the equals method.

21
void insertElementAt(Object obj, int index)
Inserts the specified object as a component in this vector at the specified
index.
22
booleanisEmpty()
Tests if this vector has no components.

23
Object lastElement()
Returns the last component of the vector.

24
int lastIndexOf(Object elem)
Returns the index of the last occurrence of the specified object in this
vector.

25
int lastIndexOf(Object elem, int index)
Searches backwards for the specified object, starting from the specified
index, and returns an index to it.

26
Object remove(int index)
Removes the element at the specified position in this vector.

27
boolean remove(Object o)
Removes the first occurrence of the specified element in this vector, If the
vector does not contain the element, it is unchanged.

28
booleanremoveAll(Collection c)
Removes from this vector all of its elements that are contained in the
specified Collection.

29
void removeAllElements()
Removes all components from this vector and sets its size to zero.

30
booleanremoveElement(Object obj)
Removes the first (lowest-indexed) occurrence of the argument from this
vector.

31
void removeElementAt(int index)
removeElementAt(int index).
32
protected void removeRange(int fromIndex, int toIndex)
Removes from this List all of the elements whose index is between
fromIndex, inclusive and toIndex, exclusive.

33
boolean retainAll(Collection c)
Retains only the elements in this vector that are contained in the specified
Collection.

34
Object set(int index, Object element)
Replaces the element at the specified position in this vector with the
specified element.

35
void setElementAt(Object obj, int index)
Sets the component at the specified index of this vector to be the specified
object.

36
void setSize(int newSize)
Sets the size of this vector.

37
int size()
Returns the number of components in this vector.

38
List subList(int fromIndex, int toIndex)
Returns a view of the portion of this List between fromIndex, inclusive, and
toIndex, exclusive.

39
Object[] toArray()
Returns an array containing all of the elements in this vector in the correct
order.

40
Object[] toArray(Object[] a)
Returns an array containing all of the elements in this vector in the correct
order; the runtime type of the returned array is that of the specified array.

41
String toString()
Returns a string representation of this vector, containing the String
representation of each element.

42
void trimToSize()
Trims the capacity of this vector to be the vector's current size.

Example
The following program illustrates several of the methods supported by this collection

Import java.util.*;
Public class VectorDemo{

Public static void main(String args[]){


// initial size is 3, increment is 2
Vector v =new Vector(3,2);
System.out.println("Initial size: "+v.size());
System.out.println("Initial capacity: "+v.capacity());

v.addElement(newInteger(1));
v.addElement(newInteger(2));
v.addElement(newInteger(3));
v.addElement(newInteger(4));
System.out.println("Capacity after four additions:
"+v.capacity());

v.addElement(newDouble(5.45));
System.out.println("Current capacity: "+v.capacity());

v.addElement(newDouble(6.08));
v.addElement(newInteger(7));
System.out.println("Current capacity: "+v.capacity());

v.addElement(newFloat(9.4));
v.addElement(newInteger(10));
System.out.println("Current capacity: "+v.capacity());

v.addElement(newInteger(11));
v.addElement(newInteger(12));
System.out.println("First element: "+(Integer)v.firstElement());
System.out.println("Last element: "+(Integer)v.lastElement());

if(v.contains(newInteger(3)))
System.out.println("Vector contains 3.");

// enumerate the elements in the vector.


Enumeration vEnum=v.elements();
System.out.println("\nElements in vector:");
while(vEnum.hasMoreElements())
System.out.print(vEnum.nextElement()+" ");
System.out.println();
}
}

This will produce the following result −

Output
Initial size: 0
Initial capacity: 3
Capacity after four additions: 5
Current capacity: 5
Current capacity: 7
Current capacity: 9
First element: 1
Last element: 12
Vector contains 3.

Elements in vector:
1 2 3 4 5.45 6.08 7 9.4 10 11 12
Java - The Stack Class
• Stack is a subclass of Vector that implements a standard last-in, first-out
stack.
• Stack only defines the default constructor, which creates an empty stack.
• Stack includes all the methods defined by Vector, and adds several of its
own.
• Apart from the methods inherited from its parent class Vector, Stack defines
the following methods −

Sr.No. Method & Description

1
boolean empty()
Tests if this stack is empty. Returns true if the stack is empty, and returns
false if the stack contains elements.

2
Object peek( )
Returns the element on the top of the stack, but does not remove it.

3
Object pop( )
Returns the element on the top of the stack, removing it in the process.

4
Object push(Object element)
Pushes the element onto the stack. Element is also returned.

5
int search(Object element)
Searches for element in the stack. If found, its offset from the top of the
stack is returned. Otherwise, -1 is returned.

Example
The following program illustrates several of the methods supported by this collection

Import java.util.*;
Public class StackDemo{

Static void showpush(Stackst,int a){


st.push(newInteger(a));
System.out.println("push("+ a +")");
System.out.println("stack: "+st);
}

Static void showpop(Stackst){


System.out.print("pop -> ");
Integer a =(Integer)st.pop();
System.out.println(a);
System.out.println("stack: "+st);
}

Public static void main(String args[]){


Stackst=newStack();
System.out.println("stack: "+st);
showpush(st,42);
showpush(st,66);
showpush(st,99);
showpop(st);
showpop(st);
showpop(st);
try{
showpop(st);
}catch(EmptyStackException e){
System.out.println("empty stack");
}
}
}

This will produce the following result −

Output
stack: [ ]
push(42)
stack: [42]
push(66)
stack: [42, 66]
push(99)
stack: [42, 66, 99]
pop -> 99
stack: [42, 66]
pop -> 66
stack: [42]
pop -> 42
stack: [ ]
pop -> empty stack
Java - The Hashtable Class

• Hashtable was part of the original java.util and is a concrete implementation


of a Dictionary.
• Java 2 re-engineered Hashtable so that it also implements the Map interface.
Thus, Hashtable is now integrated into the collections framework. It is similar
to HashMap, but is synchronized.
• Like HashMap, Hashtable stores key/value pairs in a hash table.
• When using a Hashtable, you specify an object that is used as a key, and the
value that you want linked to that key.
• The key is then hashed, and the resulting hash code is used as the index at
which the value is stored within the table.
• Following is the list of constructors provided by the HashTable class.

Sr.No Constructor & Description

1
Hashtable( )
This is the default constructor of the hash table it instantiates the Hashtable
class.

2
Hashtable(int size)
This constructor accepts an integer parameter and creates a hash table that
has an initial size specified by integer value size.

3
Hashtable(int size, float fillRatio)
This creates a hash table that has an initial size specified by size and a fill
ratio specified by fillRatio. This ratio must be between 0.0 and 1.0, and it
determines how full the hash table can be before it is resized upward.

4
Hashtable(Map < ? extends K, ? extends V > t)
This constructs a Hashtable with the given mappings.

Apart from the methods defined by Map interface, Hashtable defines the following
methods −

Sr.No Method & Description


1
void clear( )
Resets and empties the hash table.

2
Object clone( )
Returns a duplicate of the invoking object.

3
boolean contains(Object value)
Returns true if some value equal to the value exists within the hash table.
Returns false if the value isn't found.

4
Boolean containsKey(Object key)
Returns true if some key equal to the key exists within the hash table.
Returns false if the key isn't found.

5
Boolean containsValue(Object value)
Returns true if some value equal to the value exists within the hash table.
Returns false if the value isn't found.

6
Enumeration elements( )
Returns an enumeration of the values contained in the hash table.

7
Object get(Object key)
Returns the object that contains the value associated with the key. If the key
is not in the hash table, a null object is returned.

8
boolean isEmpty( )
Returns true if the hash table is empty; returns false if it contains at least
one key.

9
Enumeration keys( )
Returns an enumeration of the keys contained in the hash table.

10
Object put(Object key, Object value)
Inserts a key and a value into the hash table. Returns null if the key isn't
already in the hash table; returns the previous value associated with the key
if the key is already in the hash table.

11
void rehash( )
Increases the size of the hash table and rehashes all of its keys.

12
Object remove(Object key)
Removes the key and its value. Returns the value associated with the key. If
the key is not in the hash table, a null object is returned.

13
int size( )
Returns the number of entries in the hash table.

14
String toString( )
Returns the string equivalent of a hash table.

Example
The following program illustrates several of the methods supported by this data
structure −
Import java.util.*;
Public class HashTableDemo{

Public static void main(String args[]){


// Create a hash map
Hashtable balance =new Hashtable();
Enumeration names;
String str;
doublebal;

balance.put("Zara",newDouble(3434.34));
balance.put("Mahnaz",newDouble(123.22));
balance.put("Ayan",newDouble(1378.00));
balance.put("Daisy",newDouble(99.22));
balance.put("Qadir",newDouble(-19.08));

// Show all balances in hash table.


names =balance.keys();

while(names.hasMoreElements()){
str =(String)names.nextElement();
System.out.println(str +": "+balance.get(str));
}
System.out.println();
// Deposit 1,000 into Zara's account
bal=((Double)balance.get("Zara")).doubleValue();
balance.put("Zara",newDouble(bal+1000));
System.out.println("Zara's new balance: "+balance.get("Zara"));
}
}

This will produce the following result −

Output
Qadir: -19.08
Zara: 3434.34
Mahnaz: 123.22
Daisy: 99.22
Ayan: 1378.0

Zara's new balance: 4434.34


Java - The Properties Class

• Properties is a subclass of Hashtable.


• It is used to maintain lists of values in which the key is a String and the value
is also a String.
• The Properties class is used by many other Java classes.
• For example, it is the type of object returned by System.getProperties( )
when obtaining environmental values.
• Properties define the following instance variable. This variable holds a default
property list associated with a Properties object.
Following is the list of constructors provided by the properties class.

Sr.No. Constructor & Description

1
Properties( )
This constructor creates a Properties object that has no default values.

2
Properties(Properties propDefault)
Creates an object that uses propDefault for its default values. In both
cases, the property list is empty.

Apart from the methods defined by Hashtable, Properties define the following
methods −

Sr.No. Method & Description

1
String getProperty(String key)
Returns the value associated with the key. A null object is returned if the
key is neither in the list nor in the default property list.

2
String getProperty(String key, String defaultProperty)
Returns the value associated with the key; defaultProperty is returned if the
key is neither in the list nor in the default property list.

3
void list(PrintStreamstreamOut)
Sends the property list to the output stream linked to streamOut.

4
void list(PrintWriterstreamOut)
Sends the property list to the output stream linked to streamOut.

5
void load(InputStreamstreamIn) throws IOException
Inputs a property list from the input stream linked to streamIn.

6
Enumeration propertyNames( )
Returns an enumeration of the keys. This includes those keys found in the
default property list, too.

7
Object setProperty(String key, String value)
Associates value with the key. Returns the previous value associated with
the key, or returns null if no such association exists.

8
void store(OutputStreamstreamOut, String description)
After writing the string specified by description, the property list is written to
the output stream linked to streamOut.

Example
The following program illustrates several of the methods supported by this data
structure −
Import java.util.*;
Public class PropDemo{

Public static void main(String args[]){


Properties capitals =new Properties();
Set states;
String str;

capitals.put("Illinois","Springfield");
capitals.put("Missouri","Jefferson City");
capitals.put("Washington","Olympia");
capitals.put("California","Sacramento");
capitals.put("Indiana","Indianapolis");

// Show all states and capitals in hashtable.


states =capitals.keySet();// get set-view of keys
Iterator itr=states.iterator();
while(itr.hasNext()){
str =(String)itr.next();
System.out.println("The capital of "+ str +" is "+
capitals.getProperty(str)+".");
}
System.out.println();

// look for state not in list -- specify default


str =capitals.getProperty("Florida","Not Found");
System.out.println("The capital of Florida is "+ str +".");
}
}

This will produce the following result −

Output
The capital of Missouri is Jefferson City.
The capital of Illinois is Springfield.
The capital of Indiana is Indianapolis.
The capital of California is Sacramento.
The capital of Washington is Olympia.

The capital of Florida is Not Found.


Java Calendar Class
Java Calendar class is an abstract class that provides methods for converting date
between a specific instant in time and a set of calendar fields such as MONTH, YEAR,
HOUR, etc. It inherits Object class and implements the Comparable interface.

Java Calendar Class Example


import java.util.Calendar;
public class CalendarExample1 {
public static void main(String[] args) {
Calendar calendar = Calendar.getInstance();
System.out.println("The current date is : " + calendar.getTime());
calendar.add(Calendar.DATE, -15);
System.out.println("15 days ago: " + calendar.getTime());
calendar.add(Calendar.MONTH, 4);
System.out.println("4 months later: " + calendar.getTime());
calendar.add(Calendar.YEAR, 2);
System.out.println("2 years later: " + calendar.getTime());
}
}
StringTokenizer in Java
• The java.util.StringTokenizer class allows you to break a String into tokens.
• It doesn't provide the facility to differentiate numbers, quoted strings,
identifiers etc. like StreamTokenizer class.
• In the StringTokenizer class, the delimiters can be provided at the time of
creation or one by one to the tokens.

Constructors of the StringTokenizer Class


There are 3 constructors defined in the StringTokenizer class.

Constructor Description

StringTokenizer(String str) It creates StringTokenizer with specified string.

StringTokenizer(String str, It creates StringTokenizer with specified string and


String delim) delimiter.

StringTokenizer(String str, It creates StringTokenizer with specified string, delimiter


String delim, boolean and returnValue. If return value is true, delimiter characters
returnValue) are considered to be tokens. If it is false, delimiter
characters serve to separate tokens.

Methods of the StringTokenizer Class


The six useful methods of the StringTokenizer class are as follows:

Methods Description

boolean hasMoreTokens() It checks if there is more tokens available.

String nextToken() It returns the next token from the StringTokenizer object.

String nextToken(String delim) It returns the next token based on the delimiter.
boolean hasMoreElements() It is the same as hasMoreTokens() method.

Object nextElement() It is the same as nextToken() but its return type is Object.

int countTokens() It returns the total number of tokens.

Example of StringTokenizer Class


Simple.java

// program on StringTokenizer class and its methods hasMoreTokens() and


nextToken().

import java.util.StringTokenizer;
public class Simple{
public static void main(String args[]){
StringTokenizer st = new StringTokenizer("my name is Laxmi"," ");
while (st.hasMoreTokens()) {
System.out.println(st.nextToken());
}
}
}

Example of nextToken(String delim) method of the


StringTokenizer class
Test.java

import java.util.*;

public class Test {


public static void main(String[] args) {
StringTokenizer st = new StringTokenizer("my,name,is,Laxmi");

// printing next token


System.out.println("Next token is : " + st.nextToken(","));
}
}

Output:

Next token is : my
Note: The StringTokenizer class is deprecated now. It is recommended to use the
split() method of the String class or the Pattern class that belongs to the
java.util.regex package.

Example of hasMoreTokens() method of the


StringTokenizer class
• This method returns true if more tokens are available in the tokenizer String
otherwise returns false.

StringTokenizer1.java

import java.util.StringTokenizer;
public class StringTokenizer1
{
/* Driver Code */
public static void main(String args[])
{
/* StringTokenizer object */
StringTokenizer st = new StringTokenizer("Demonstrating methods from StringTokenizer class
"," ");
/* Checks if the String has any more tokens */
while (st.hasMoreTokens())
{
System.out.println(st.nextToken());
}
}
}

Output:

Demonstrating
methods
from
StringTokenizer
class
The above Java program shows the use of two methods hasMoreTokens() and
nextToken() of StringTokenizer class.
Example of hasMoreElements() method of the
StringTokenizer class
• This method returns the same value as hasMoreTokens() method of
StringTokenizer class.
• The only difference is this class can implement the Enumeration interface.

StringTokenizer2.java

import java.util.StringTokenizer;
public class StringTokenizer2
{
public static void main(String args[])
{
StringTokenizer st = new StringTokenizer("Hello everyone I am a Java developer"," ");
while (st.hasMoreElements())
{
System.out.println(st.nextToken());
}
}
}

Output:

Hello
everyone
I
am
a
Java
developer

The above code demonstrates the use of hasMoreElements() method.

Example of nextElement() method of the StringTokenizer


class
• nextElement() returns the next token object in the tokenizer String.
• It can implement Enumeration interface.

StringTokenizer3.java

import java.util.StringTokenizer;
public class StringTokenizer3
{
/* Driver Code */
public static void main(String args[])
{
/* StringTokenizer object */
StringTokenizer st = new StringTokenizer("Hello Everyone Have a nice day"," ");
/* Checks if the String has any more tokens */
while (st.hasMoreTokens())
{
/* Prints the elements from the String */
System.out.println(st.nextElement());
}
}
}

Output:

Hello
Everyone
Have
a
nice
day

The above code demonstrates the use of nextElement() method.

Example of countTokens() method of the StringTokenizer


class
This method calculates the number of tokens present in the tokenizer String.

StringTokenizer4.java

import java.util.StringTokenizer;
public class StringTokenizer3
{
/* Driver Code */
public static void main(String args[])
{
/* StringTokenizer object */
StringTokenizer st = new StringTokenizer("Hello Everyone Have a nice day"," ");
/* Prints the number of tokens present in the String */
System.out.println("Total number of Tokens: "+st.countTokens());
}
}

Output:

Total number of Tokens: 6

The above Java code demonstrates the countTokens() method of StringTokenizer()


class.

You might also like