Download as docx, pdf, or txt
Download as docx, pdf, or txt
You are on page 1of 18

Collections in JAVA

 Before learning collections one needs to learn about WRAPPER CLASSES.


 A wrapper class is a class whose object wraps or contains a primitive data type.
 That is if we want to convert a variable of any data type into object then we must make use of wrapper
classes.
 Study of wrapper classes is important because, collections classes and interfaces deal with data only in terms
of objects. Thus, before learning about collections one needs to know about wrapper classes.

PRIMITIVE DATA TYPE WRAPPER CLASS


int Integer
char Character
double Double
long Long
short Short
float Float
boolean Boolean

 Number is an abstract class whose sub classes are wrapper classes that are shown in the above table.

Methods Implemented by all Subclasses of Number

Method Description

byte byteValue()
short shortValue()
int intValue()
Converts the value of this Number object to the primitive data type returned.
long longValue()
float floatValue()
double doubleValue()

int compareTo(Byte anotherByte)


int compareTo(Double anotherDouble)
int compareTo(Float anotherFloat)
Compares this Number object to the argument.
int compareTo(Integer anotherInteger)
int compareTo(Long anotherLong)
int compareTo(Short anotherShort)

 All the wrapper classes are declared final. That means you cannot derive a subclass from any of them.All the
wrapper classes except Boolean and Character are subclasses of an abstract class called Number, whereas
Boolean and Character are derived directly from the Object class.All of the wrapper classes except Character
provide two constructors: one that takes a primitive of the type being constructed, and one that takes a String
representation of the type being constructed.

1
Collections in JAVA

PROGRAM TO DEMONSTRATE WRAPPER CLASSES

import java.io.*;
class wrapperdemo
{
public static void main(String[] args)
{

int x=20;
Integer i = new Integer(x);
System.out.println(i);
//converts integer variable x into object

int y = i.intValue();
//retrives value present in object i
System.out.println(y);

double d=20.5;
Double d1 = new Double(d);
//converts integer variable x into object
System.out.println(d1);

double k = d1.doubleValue();
//retrives value present in object k
System.out.println(k);
}
}
_____________________________________________________________________________
UNIT- III
Exploring Java Language, Collections Overview, Collections Interfaces, Collections Classes, Iterators, Random
Access Interface, Maps, Comparators, Arrays, Legacy classes and interfaces, String tokenizer, BitSet , Date,
Calendar, Timer

____________________________________________________________________________________________

Collections Overview, Collections Interfaces, Collections


Classes,Maps,Arrays

Collections in java is a framework that provides an architecture to store and manipulate the group of
objects.

All the operations that you perform on a data such as searching, sorting, insertion, manipulation, deletion etc. can
be performed by Java Collections.

Java Collection simply means a single unit of objects. Java Collection framework provides many interfaces (Set,
List, Queue, Deque etc.) and classes (ArrayList, Vector, LinkedList, PriorityQueue, HashSet, LinkedHashSet,
TreeSet etc).

What is Collection in java

Collection represents a single unit of objects i.e. a group.

What is framework in java


 provides readymade architecture.
 represents set of classes and interface.
 is optional.

2
Collections in JAVA

Prior to Java 2, Java provided ad hoc classes such as Dictionary, Vector, Stack, and Properties to store and
manipulate groups of objects. Although these classes were quite useful, they lacked a central, unifying theme.
Thus, the way that you used Vector was different from the way that you used Properties.

The collections framework was designed to meet several goals.

1. The framework had to be high-performance. The implementations for the fundamental collections
(dynamic arrays, linked lists, trees, and hash tables) are highly efficient.

2. The framework had to allow different types of collections to work in a similar manner and with a high
degree of interoperability.

3. Extending and/or adapting a collection had to be easy.

What is Collection framework

Collection framework represents a unified architecture for storing and manipulating group of objects. It has:
1. Interfaces and its implementations i.e. classes
2. Algorithm

Hierarchy of Collection Framework :The java.util package contains all the classes and interfaces for Collection
framework.

3
Collections in JAVA

Implementation
Interface type
classes

HashSet<T>
Set<T> LinkedHashSet<T>
TreeSet<T>
this table represents the interfaces and
their implementation classes of Collection
Stack<T>
frame work
LinkedList<T>
ArrayList<T>
Vector<T>
List<T>

Queue<T> LinkedList<T>

HashMap<k,v>
Map<k,v>
HashTable<k,v>

Methods of Collection interface

There are many methods declared in the Collection interface. They are as follows:

No. Method Description

1 public boolean add(Object element) is used to insert an element in this collection.

2 public boolean addAll(collection c) is used to insert the specified collection elements in the invoking collection.

3 public boolean remove(Object is used to delete an element from this collection.


element)

4 public boolean removeAll(Collection is used to delete all the elements of specified collection from the invoking
c) collection.

5 public boolean retainAll(Collection c) is used to delete all the elements of invoking collection except the specified
collection.

6 public int size() return the total number of elements in the collection.

7 public void clear() removes the total no of element from the collection.

8 public boolean contains(object is used to search an element.

4
Collections in JAVA

element)

9 public boolean containsAll(Collection is used to search the specified collection in this collection.
c)

1 public Iterator iterator() returns an iterator.


0

1 public Object[] toArray() converts collection into array.


1

1 public boolean isEmpty() checks if collection is empty.


2

1 public boolean equals(Object matches two collection.


3 element)

1 public int hashCode() returns the hashcode number for collection.


4

 Java collection framework was non-generic before JDK 1.5. Since 1.5, it is generic.

 Java new generic collection allows you to have only one type of object in collection. Now it is
type safe so typecasting is not required at run time.

Let's see the old non-generic example of creating java collection.

ArrayList al=new ArrayList();//creating old non-generic arraylist  

Let's see the new generic example of creating java collection.

ArrayList<String> al=new ArrayList<String>();//creating new generic arraylist  

In generic collection, we specify the type in angular braces. Now ArrayList is forced to have only specified type of
objects in it. If you try to add another type of object, it gives compile time error.

Java ArrayList class


 Java ArrayList class uses a dynamic array for storing the elements.It extends AbstractList class and
implements List interface.
 Java ArrayList class can contain duplicate elements.
 Java ArrayList class maintains insertion order.
 Java ArrayList class is non synchronized.
 Java ArrayList allows random access because array works at the index basis.
 In Java ArrayList class, manipulation is slow because a lot of shifting needs to be occurred if any element
is removed from the array list.

Program to demonstrate array list class

import java.util.*;   output:
class TestCollection1{  
 public static void main(String args[]){  
Ravi
   
Vijay
Ravi
Ajay 5
Collections in JAVA

  ArrayList<String> al=new ArrayList<String>();//creating arraylist  
  al.add("Ravi");//adding object in arraylist  
  al.add("Vijay");  
  al.add("Ravi");  
  al.add("Ajay");  
  
  Iterator itr=al.iterator();//getting Iterator from arraylist to traverse elements  
  while(itr.hasNext()){  
   System.out.println(itr.next());  
  }  
 }  
}  

Java Linked List class


 Java LinkedList class uses doubly linked list to store the elements. It extends the AbstractList class and
implements List and Deque interfaces.
 Java LinkedList class can contain duplicate elements.
 Java LinkedList class maintains insertion order.
 Java LinkedList class is non synchronized.
 In Java LinkedList class, manipulation is fast because no shifting needs to be occurred.
 Java LinkedList class can be used as list, stack or queue.

Program to demonstrate linked list class

import java.util.*;  
public class TestCollection7{   output:
 public static void main(String args[]){  
   
  LinkedList<String> al=new LinkedList<String>();   Ravi
  al.add("Ravi");   Vijay
  al.add("Vijay");   Ravi
  al.add("Ravi");   Ajay
  al.add("Ajay");  
  
  Iterator<String> itr=al.iterator();  
  while(itr.hasNext()){  
   System.out.println(itr.next());  
  }  
 }  
}  

ArrayList LinkedList

1) ArrayList internally uses dynamic array to store the LinkedList internally uses doubly linked list to
elements. store the elements.

2) Manipulation with ArrayList is slow because it Manipulation with LinkedList is faster than ArrayList


internally uses array. If any element is removed from because it uses doubly linked list so no bit shifting is
the array, all the bits are shifted in memory. required in memory.

6
Collections in JAVA

3) ArrayList class can act as a list only because it LinkedList class can act as a list and queue both
implements List only. because it implements List and Deque interfaces.

4) ArrayList is better for storing and accessing data. LinkedList is better for manipulating data.

Java LinkedHashSet class:


 contains unique elements only like HashSet. It extends HashSet class and implements Set interface.
 maintains insertion order.

Hierarchy of LinkedHashSet class:

program to demonstrate linked hash set class


import java.util.*;  
class TestCollection10{  
 public static void main(String args[]){  
   
  LinkedHashSet<String> al=new LinkedHashSet<String>();   output:
  al.add("Ravi");  
  al.add("Vijay");   Ravi
  al.add("Ravi");  
Vijay
  al.add("Ajay");  
   Ajay
  Iterator<String> itr=al.iterator();  
  while(itr.hasNext()){  
   System.out.println(itr.next());  
  }  
 }  
}  

Java TreeSet class


 contains unique elements only like HashSet. The TreeSet class implements NavigableSet interface that
extends the SortedSet interface.

 maintains ascending order.

program to demonstrate tree set class output:

import java.util.*;   Ajay
Ravi
Vijay
7
Collections in JAVA

class TestCollection11{  
 public static void main(String args[]){  
   
  TreeSet<String> al=new TreeSet<String>();  
  al.add("Ravi");  
  al.add("Vijay");  
  al.add("Ravi");  
  al.add("Ajay");  
  
  Iterator<String> itr=al.iterator();  
  while(itr.hasNext()){  
   System.out.println(itr.next());  
  }  
 }  
}  

Hierarchy of TreeSet class:

Java HashSet class


o uses hashtable to store the elements.It extends AbstractSet class and implements Set interface.
o contains unique elements only.

Difference between List and Set: List can contain duplicate elements whereas Set contains unique elements
only.

Hierarchy of HashSet class:

8
Collections in JAVA

program to demonstrate hash set class


import java.util.*;  
class TestCollection9{  
 public static void main(String args[]){  
    output:
  HashSet<String> al=new HashSet<String>();  
  al.add("Ravi");  
  al.add("Vijay");   Ajay
  al.add("Ravi");   Vijay
  al.add("Ajay");  
   Ravi
  Iterator<String> itr=al.iterator();  
  while(itr.hasNext()){  
   System.out.println(itr.next());  
  }  
 }  
}  

Java HashMap class


o A HashMap contains values based on the key. It implements the Map interface and extends AbstractMap
class.
o It contains only unique elements.
o It may have one null key and multiple null values.
o It maintains no order.

Hierarchy of HashMap class:

program to demonstrate hashmap class


import java.util.*;  
class TestCollection13{   output:
 public static void main(String args[]){  
    100 Amit
  HashMap<Integer,String> hm=new HashMap<Integer,String>();   101 Vijay
   102 Rahul

9
Collections in JAVA

  hm.put(100,"Amit");  
  hm.put(101,"Vijay");  
  hm.put(102,"Rahul");  
  
  for(Map.Entry m:hm.entrySet()){  
   System.out.println(m.getKey()+" "+m.getValue());  
  }  
 }  
}  

Java LinkedHashMap class


o A LinkedHashMap contains values based on the key. It implements the Map interface and extends
HashMap class.
o It contains only unique elements.
o It may have one null key and multiple null values.
o It is same as HashMap instead maintains insertion order.

Hierarchy of LinkedHashMap class:

program to demonstrate linked hash map class


import java.util.*;  
class TestCollection14{  
 public static void main(String args[]){   output:
   
  LinkedHashMap<Integer,String> hm=new LinkedHashMap<Integer,String>();  
   100 Amit
  hm.put(100,"Amit");  
101 Vijay
  hm.put(101,"Vijay");  
  hm.put(102,"Rahul");   103 Rahul
  
for(Map.Entry m:hm.entrySet()){  
   System.out.println(m.getKey()+" "+m.getValue());  
  }  
 }  
}  

Java TreeMap class


o A TreeMap contains values based on the key. It implements the NavigableMap interface and extends
AbstractMap class.
o It contains only unique elements.
o It cannot have null key but can have multiple null values.
o It is same as HashMap instead maintains ascending order.

10
Collections in JAVA

Hierarchy of TreeMap class:

program to demonstrate tree map class


import java.util.*;  
class TestCollection15{  
 public static void main(String args[]){  
output:
   
  TreeMap<Integer,String> hm=new TreeMap<Integer,String>();   100 Amit
  
  hm.put(100,"Amit");   101 Vijay
  hm.put(102,"Ravi");   102 Ravi
  hm.put(101,"Vijay");  
  hm.put(103,"Rahul");   103 Rahul
  
  for(Map.Entry m:hm.entrySet()){  
   System.out.println(m.getKey()+" "+m.getValue());  
  }  
 }  
}  

Java Hashtable class


o A Hashtable is an array of list.Each list is known as a bucket.The position of bucket is identified by calling
the hashcode() method.A Hashtable contains values based on the key. It implements the Map interface
and extends Dictionary class.
o It contains only unique elements.
o It may have not have any null key or value.
o It is synchronized.

program for hash table


import java.util.*;  
class TestCollection16{   output:
 public static void main(String args[]){  
   
  Hashtable<Integer,String> hm=new Hashtable<Integer,String>();   103 Rahul
   102 Ravi
  hm.put(100,"Amit");  
  hm.put(102,"Ravi");   101 Vijay
  hm.put(101,"Vijay");   100 Amit
  hm.put(103,"Rahul");  
  
  for(Map.Entry m:hm.entrySet()){  
   System.out.println(m.getKey()+" "+m.getValue());  
  }  
 }  
}  

11
Collections in JAVA

HashMap Hashtable

1) HashMap is non synchronized. It is not-thread safe and Hashtable is synchronized. It is


can't be shared between many threads without proper thread-safe and can be shared with
synchronization code. many threads.

2) HashMap allows one null key and multiple null values. Hashtable doesn't allow any null key
or value.

3) HashMap is a new class introduced in JDK 1.2. Hashtable is a legacy class.

4) HashMap is fast. Hashtable is slow.

5) We can make the HashMap as synchronized by calling this Hashtable is internally synchronized
code and can't be unsynchronized.
Map m = Collections.synchronizedMap(hashMap);

6) HashMap is traversed by Iterator. Hashtable is traversed by


Enumerator and Iterator.

7) Iterator in HashMap is fail-fast. Enumerator in Hashtable is not fail-


fast.

8) HashMap inherits AbstractMap class. Hashtable inherits Dictionary class

Iterators

There are 4 ways to retrieve the elements from Collection objects:

1. for-each loop
2. Iterator interface
3. ListIterator interface
4. Enumeration interface

for-each loop:

 the difference between for loop and for-each loop is that for loop is INDEX BASED RETRIEVAL and for-each
loop is OBJECT BASED RETRIEVAL.
 Syntax of for-each loop is:

for(variable : collection-object)
{
Statements;
}

 Here, the variable assumes each element of the collection-object and the loop is executed as many times
as there are number of elements in the collection-object.
 If the collection-object has ‘n’ elements the loop is executed exactly ‘n’ times and variable stores each
element in each step.

Iterator interface:

 Iterator is an interface that contains methods to retrieve the elements one by one from a collection object.
It has 3 methods:

12
Collections in JAVA

1. boolean hasNext() : this method returns true if the iterator has more elements
2. element next() : this method returns the next element in the iterator
3. void remove() : this method removes from the collection the last element returned by the iterator.

ListIterator Interface:
.
 it is as interface that contains methods to retrieve elements from a collection object in both forward and
reverse direction ( top-bottom and bottom-top). It has these methods:

1. boolean hasNext() : this method returns true if the iterator has more elements in forward direction
2. boolean hasPrevious() : this method returns true if the iterator has more elements in backward
direction
3. element next() : this method returns the next element in the iterator
4. element previous() : this method returns the previous element in the iterator
5. void remove() : this method removes from the collection the last element returned by the iterator.

What is the difference between iterator and list iterator?


 Iterator retrieves elements only in forward direction where as list iterator retrieves elements in both
forward and backward directions.

Enumeration Interface:

It is useful to retrieve elements one by one just like iterator. It has the following methods:

1. boolean hasMoreElements() : this method tests if the enumeration has any more elements or not.
2. element nextElement() : this returns next element that is available in the enumeration.

Random Access Interface

 Java 2, version 1.4 adds the RandomAccess interface.


 This interface contains no members.
 However, by implementing this interface, a collection signals that it supports efficient random access to its
elements.
 Although a collection might support random access, it might not do so efficiently.
 By checking for the RandomAccess interface, client code can determine at run time whether a collection
is suitable for certain types of random access operations—especially as they apply to large collections.
(You can use instanceof to determine if a class implements an interface.)
 RandomAccess is implemented by ArrayList and by the legacy Vector class.

Comparators

 The java.util package offers an interface called comparator that is useful to impose total ordering on a
collection of elements.
 It can be used to sort the elements ( objects ) of an array into ascending or descending order.
 Comparator can be written as:

interface Comparator<T>

 Here T represents the type of elements ( objects ) compared by comparator.

 The Comparator interface defines two methods: compare( ) and equals( ).

 The compare( ) method, shown here, compares two elements for order:

int compare(Object obj1, Object obj2)

obj1 and obj2 are the objects to be compared. This method returns zero if the objects are
equal. It returns a positive value if obj1 is greater than obj2. Otherwise, a negative value
is returned. The method can throw a ClassCastException if the types of the objects are
not compatible for comparison. By overriding compare( ), you can alter the way that
objects are ordered. For example, to sort in reverse order, you can create a comparator
that reverses the outcome of a comparison.
THE JAVA LIBRARY

13
Collections in JAVA

 The equals( ) method, shown here, tests whether an object equals the invoking comparator

boolean equals(Object obj)

obj is the object to be tested for equality. The method returns true if obj and the invoking object are both
Comparator objects and use the same ordering. Otherwise, it returns false. Overriding equals( ) is unnecessary,
and most simple comparators will not do so.

// Use a custom comparator.


import java.util.*;
// A reverse comparator for strings.
class MyComp implements Comparator
{
public int compare(Object a, Object b)
{
String aStr, bStr;
aStr = (String) a;
bStr = (String) b;
// reverse the comparison
return bStr.compareTo(aStr);
}
// no need to override equals
}
class CompDemo
{
public static void main(String args[])
{
// Create a tree set
TreeSet ts = new TreeSet(new MyComp());
// Add elements to the tree set
ts.add("C");
ts.add("A");
ts.add("B");
ts.add("E");
ts.add("F");
ts.add("D");
// Get an iterator
Iterator i = ts.iterator();
// Display elements
while(i.hasNext()) {
Object element = i.next();
System.out.print(element + " ");
}
System.out.println();
}
}

As the following output shows, the tree is now stored in reverse order:

FEDCBA

Legacy classes and interfaces

The original version of java.util did not include the collections framework. Instead, it defined several classes and
an interface that provided an ad hoc method of storing objects. With the addition of collections by Java 2, several
of the original classes were reengineered to support the collection interfaces.

Thus, they are fully compatible with the framework. While no classes have actually been deprecated, one has been
rendered obsolete. Of course, where a collection duplicates the functionality of a legacy class, you will usually want
to use the collection for new code. In general, the legacy classes are supported because there is still code
that uses them. One other point: None of the collection classes are synchronized, but all the legacy classes are
synchronized. This distinction may be important in some situations. Of course, you can easily synchronize
collections, too, by using one of the algorithms provided by Collections.

14
Collections in JAVA

The legacy classes defined by java.util are shown here:

Dictionary Hashtable Properties Stack Vector

There is one legacy interface called Enumeration.

STRING TOKENIZER

The processing of text often consists of parsing a formatted input string. Parsing is the division of text into a set of
discrete parts, or tokens, which in a certain sequence can convey a semantic meaning. The StringTokenizer class
provides the first step in this parsing process, often called the lexer (lexical analyzer) or scanner.

StringTokenizer implements the Enumeration interface. Therefore, given an input string, you can
enumerate the individual tokens contained in it using StringTokenizer.

To use StringTokenizer, you specify an input string and a string that contains delimiters. Delimiters are
characters that separate tokens. Each character in the delimiters string is considered a valid delimiter—
for example, “,;:” sets the delimiters to a comma, semicolon, and colon.
The default set of delimiters consists of the whitespace characters: space, tab, newline, and carriage
return.

The StringTokenizer constructors are shown here:

StringTokenizer(String str)
StringTokenizer(String str, String delimiters)
StringTokenizer(String str, String delimiters, boolean delimAsToken)

In all versions, str is the string that will be tokenized. In the first version, the default delimiters are used. In the
second and third versions, delimiters is a string that specifies the delimiters. In the third version, if delimAsToken is
true, then the delimiters are also returned as tokens when the string is parsed. Otherwise, the delimiters are not
returned.
Delimiters are not returned as tokens by the first two forms.

Methods of the string tokenizer class are:

 int countTokens( ) : Using the current set of delimiters, the method determines the number of tokens
left to be parsed and returns the result.
 boolean hasMoreElements( ) : Returns true if one or more tokens remain in the string else returns
false
 boolean hasMoreTokens( ) : Returns true if one or more tokens remain in the string else returns false
 Object nextElement( ) : Returns the next token as an Object.
 String nextToken( ) : Returns the next token as a String.
 String nextToken(String delimiters) : Returns the next token as a String and sets the delimiters
string to that specified by delimiters.

PROGRAM TO DEMONSTRATE STRING TOKENIZER:

import java.io.*;
import java.util.*;
class Count
{
public static void main(String[] a) throws IOException
{
String s;
int lc=1,wc=0,cc=0;

FileInputStream f=new FileInputStream(a[0]);


DataInputStream d=new DataInputStream(f);
while((s=d.readLine())!=null)
{
lc++;

15
Collections in JAVA

StringTokenizer s1=new StringTokenizer(s);


while(s1.hasMoreTokens())
{
String b=s1.nextToken();
wc++;
cc=cc+b.length();
}
}
System.out.println("words="+wc+"\nlines="+lc+"\n characters="+cc);
}
}
Output : java count count.java
words =43
lines=27
characters=416
BITSET CLASS

 A BitSet class creates a special type of array that holds bit values.
 This array can increase in size as needed.
 This makes it similar to a vector of bits.
 The BitSet constructors are shown here:
BitSet( )
BitSet(int size)

 The first version creates a default object.


 The second version allows you to specify its initial size (that is, the number of bits that it can hold).
 All bits are initialized to zero.
 BitSet implements the Cloneable interface and contains the following methods:

public java.util.BitSet();
public java.util.BitSet(int);
public void flip(int);
public void flip(int, int);
public void set(int);
public void set(int, boolean);
public void set(int, int);
public void set(int, int, boolean);
public void clear(int);
public void clear(int, int);
public void clear();
public boolean get(int);
public java.util.BitSet get(int, int);
public int nextSetBit(int);
public int nextClearBit(int);
public int length();
public boolean isEmpty();
public boolean intersects(java.util.BitSet);
public int cardinality();
public void and(java.util.BitSet);
public void or(java.util.BitSet);
public void xor(java.util.BitSet);
public void andNot(java.util.BitSet);
public int hashCode();
public int size();
public boolean equals(java.lang.Object);
public java.lang.Object clone();
public java.lang.String toString();

DATE CLASS

16
Collections in JAVA

 Date class is useful to display the date and time at that particular moment.
 When an object is created to Date class it contains the system date and time by default
 To create an object the syntax is

Date d = new Date();

 Now ‘d’ contains the system date and time.


 Once the date class object is created it should be formatted using the following methods of DateFormat
class of java.text package.

DateFormat fmt = new DateFormat.getDateInstance(formatconst, region);

 This method is useful to store format information for date value into DateFormat object fmt

DateFormat fmt = new DateFormat.getTimeInstance(formatconst, region);

 This method is useful to store format information for time into DateFormat object fmt

DateFormat fmt = new DateFormat.getDateTimeInstance(formatconst, formatconst,region);

 To specify the date and time of Date class object the method used is format( ) method

String str = fmt.format();

 The preceeding format( ) method will apply the format which is in fmt object to the Date class object ‘d’.
the formatted date and time will appear as a string in variable ‘str’. In the preceeding DateFormat
methods we used ‘formatconst’ parameter which represents one of the following values:

DateFormat.LONG ( 03 june 2012 19:43:34 O’clock GMT+ 05:30 )


DateFormat.FULL ( 03 june 2012 19:43:34 GMT+ 05:30 )
DateFormat.MEDIUM (03-06-12 19:43:34)
DateFormat.SHORT ( 03/06/2012 19:43)

 ‘region’ means one of the following values for countries in the world:
Locale.US, Locale.UK, Locale.CHINA etc.,,,

CALENDAR CLASS

 The abstract Calendar class provides a set of methods that allows you to convert a time in milliseconds to
a number of useful components.
 Some examples of the type of information that can be provided are: year, month, day, hour, minute, and
second.
 It is intended that subclasses of Calendar will provide the specific functionality to interpret
time information according to their own rules.
 This is one aspect of the Java class library that enables you to write programs that can operate in several
international environments.
 An example of such a subclass is GregorianCalendar.
 Calendar provides no public constructors.
 Calendar defines several protected instance variables.
areFieldsSet is a boolean that indicates if the time components have been set.
fields is an array of ints that holds the components of the time.
isSet is a boolean array that indicates if a specific time component has been set.
time is a long that holds the current time for this object.
isTimeSet is a boolean that indicates if the current time has been set.

METHODS OF CALENDAR CLASS:

Calendar.MONTH
Calendar.DATE
Calendar.YEAR
Calendar.MINUTE

17
Collections in JAVA

Calendar.HOUR
Calendar.SECOND
Calendar.AM_PM etc.,,

Timer and TimerTask


 Java 2, version 1.3 added an interesting and useful feature to java.util: the ability to schedule a task for
execution at some future time.
 The classes that support this are Timer and TimerTask.
 Using these classes you can create a thread that runs in the background, waiting for a specific time. When
the time arrives, the task linked to that thread is executed.
 Various options allow you to schedule a task for repeated execution, and to schedule a task to run on a
specific date.
 Although it was always possible to manually create a task that would be executed at a specific time using
the Thread class, Timer and TimerTask greatly simplify this process.
 Timer and TimerTask work together.
 Timer is the class that you will use to schedule a task for execution.
 The task being scheduled must be an instance of TimerTask.
 Thus, to schedule a task, you will first create a TimerTask object and then schedule it for execution using
an instance of Timer. TimerTask implements the Runnable interface; thus it can be used to create a
thread of execution.

 Its constructor is shown here:


TimerTask( )
 TimerTask defines the following methods and variables

static final int VIRGIN;


static final int SCHEDULED;
static final int EXECUTED;
static final int CANCELLED;
long nextExecutionTime;
long period;
protected java.util.TimerTask();
public abstract void run();
public boolean cancel();
public long scheduledExecutionTime();

18

You might also like