Java - Data Structures
The data structures provided by the Java utility
package are very powerful and perform a wide range of functions. These data
structures consist of the following interface and classes:
·
Enumeration
·
BitSet
·
Vector
·
Stack
·
Dictionary
·
Hashtable
·
Properties
All these classes are now legacy and Java-2 has
introduced a new framework called Collections Framework, which is discussed in
next tutorial:
The Enumeration:
The Enumeration interface isn't itself a data
structure, but it is very important within the context of other data
structures. The Enumeration interface defines a means to retrieve successive
elements from a data structure.
For example, Enumeration defines a method called
nextElement that is used to get the next element in a data structure that
contains multiple elements.
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. This legacy interface
has been superceded by Iterator. Although not deprecated, Enumeration is
considered obsolete for new code. However, it is used by several methods
defined by the legacy classes such as Vector and Properties, is used by several
other API classes, and is currently in widespread use in application code.
The
methods declared by Enumeration are summarized in the following table:
SNo.
|
Methods with
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. |
Prog. No.:- 91 (Enumeration interface)
import java.util.Vector;
import java.util.Enumeration;
public class EnumerationTester {
public static void main(String args[]) {
Enumeration days;
Vector dayNames = new Vector();
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());
}
}
}
Output:
C:\java>
javac EnumerationTester.java
C:\java> java EnumerationTester
Sunday
Monday
Tuesday
Wednesday
Thursday
Friday
Saturday
The BitSet
The BitSet class
implements a group of bits or flags that can be set and cleared individually. This
class is very useful in cases where you need to keep up with a set of Boolean
values; you just assign a bit to each value and set or clear it as appropriate.
A BitSet class creates a special type of array that holds bit values. The
BitSet array can increase in size as needed. This makes it similar to a vector
of bits. This is a legacy class but it has been completely re-engineered in
Java 2, version 1.4.
The BitSet defines two constructors. The
first version creates a default object:
BitSet( )
The second
version allows you to specify its initial size, i.e., the number of bits that
it can hold. All bits are initialized to zero.
BitSet(int size)
BitSet implements the Cloneable interface and defines the methods
listed in table below:
SN
|
Methods with
Description
|
1
|
void and(BitSet bitSet)
ANDs the contents of the invoking BitSet object with those specified by bitSet. The result is placed into the invoking object. |
2
|
void andNot(BitSet bitSet)
For each 1 bit in bitSet, the corresponding bit in the invoking BitSet is cleared. |
3
|
int cardinality( )
Returns the number of set bits in the invoking object. |
4
|
void clear( )
Zeros all bits. |
5
|
void clear(int index)
Zeros the bit specified by index. |
6
|
void clear(int startIndex, int endIndex)
Zeros the bits from startIndex to endIndex.1. |
7
|
Object clone( )
Duplicates the invoking BitSet object. |
8
|
boolean equals(Object bitSet)
Returns true if the invoking bit set is equivalent to the one passed in bitSet. Otherwise, the method returns false. |
9
|
void flip(int index)
Reverses the bit specified by index. ( |
10
|
void flip(int startIndex, int endIndex)
Reverses the bits from startIndex to endIndex.1. |
11
|
boolean get(int index)
Returns the current state of the bit at the specified index. |
12
|
BitSet get(int startIndex, int endIndex)
Returns a BitSet that consists of the bits from startIndex to endIndex.1. The invoking object is not changed. |
13
|
int hashCode( )
Returns the hash code for the invoking object. |
14
|
boolean intersects(BitSet bitSet)
Returns true if at least one pair of corresponding bits within the invoking object and bitSet are 1. |
15
|
boolean isEmpty( )
Returns true if all bits in the invoking object are zero. |
16
|
int length( )
Returns the number of bits required to hold the contents of the invoking BitSet. This value is determined by the location of the last 1 bit. |
17
|
int nextClearBit(int startIndex)
Returns the index of the next cleared bit, (that is, the next zero bit), starting from the index specified by startIndex |
18
|
int nextSetBit(int startIndex)
Returns the index of the next set bit (that is, the next 1 bit), starting from the index specified by startIndex. If no bit is set, .1 is returned. |
19
|
void or(BitSet bitSet)
ORs the contents of the invoking BitSet object with that specified by bitSet. The result is placed into the invoking object. |
20
|
void set(int index)
Sets the bit specified by index. |
21
|
void set(int index, boolean v)
Sets the bit specified by index to the value passed in v. true sets the bit, false clears the bit. |
22
|
void set(int startIndex, int endIndex)
Sets the bits from startIndex to endIndex.1. |
23
|
void set(int startIndex, int endIndex, boolean v)
Sets the bits from startIndex to endIndex.1, to the value passed in v. true sets the bits, false clears the bits. |
24
|
int size( )
Returns the number of bits in the invoking BitSet object. |
25
|
String toString( )
Returns the string equivalent of the invoking BitSet object. |
26
|
void xor(BitSet bitSet)
XORs the contents of the invoking BitSet object with that specified by bitSet. The result is placed into the invoking object |
Prog. No.:- 92 (BitSet interface)
import java.util.BitSet;
public class BitSetDemo {
public static void main(String args[]) {
BitSet bits1 = new BitSet(16);
BitSet bits2 = new BitSet(16);
// set some bits
for(int i=0; i<16; i++) {
if((i%2) == 0) bits1.set(i);
if((i%5) != 0) bits2.set(i);
}
System.out.println("Initial pattern in bits1: ");
System.out.println(bits1);
System.out.println("\nInitial pattern in bits2: ");
System.out.println(bits2);
// AND bits
bits2.and(bits1);
System.out.println("\nbits2 AND bits1: ");
System.out.println(bits2);
// OR bits
bits2.or(bits1);
System.out.println("\nbits2 OR bits1: ");
System.out.println(bits2);
// XOR bits
bits2.xor(bits1);
System.out.println("\nbits2 XOR bits1: ");
System.out.println(bits2);
}
}
Output:
C:\java>
javac BitSetDemo.java
C:\java> java BitSetDemo
Initial pattern in bits1:
{0, 2, 4, 6, 8, 10, 12, 14}
Initial pattern in bits2:
{1, 2, 3, 4, 6, 7, 8, 9, 11, 12, 13, 14}
bits2 AND bits1:
{2, 4, 6, 8, 12, 14}
bits2 OR bits1:
{0, 2, 4, 6, 8, 10, 12, 14}
bits2 XOR bits1:
{}
The Vector
The Vector class
is similar to a traditional Java array, except that it can grow as necessary to
accommodate new elements. Like an array, elements of a Vector object can be
accessed via an index into the vector. The nice thing about using the Vector
class is that you don't have to worry about setting it to a specific size upon
creation; it shrinks and grows automatically when necessary.
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.
The Vector class supports four constructors.
The first form creates a default vector,
which has an initial size of 10:
Vector( )
The second form creates a vector whose
initial capacity is specified by size:
Vector(int size)
The third form 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:
Vector(int size, int incr)
The fourth form creates a vector that
contains the elements of collection c:
Vector(Collection c)
Methods inherited from its parent classes,
Vector defines the following methods:
SN
|
Methods with
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
|
boolean containsAll(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
|
boolean isEmpty()
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
|
boolean removeAll(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
|
boolean removeElement(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. |
Prog. No.:- 93 (Vector interface)
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(new Integer(1));
v.addElement(new Integer(2));
v.addElement(new Integer(3));
v.addElement(new Integer(4));
System.out.println("Capacity after four additions: " +
v.capacity());
v.addElement(new Double(5.45));
System.out.println("Current capacity: " +
v.capacity());
v.addElement(new Double(6.08));
v.addElement(new Integer(7));
System.out.println("Current capacity: " +
v.capacity());
v.addElement(new Float(9.4));
v.addElement(new Integer(10));
System.out.println("Current capacity: " +
v.capacity());
v.addElement(new Integer(11));
v.addElement(new Integer(12));
System.out.println("First element: " +
(Integer)v.firstElement());
System.out.println("Last element: " +
(Integer)v.lastElement());
if(v.contains(new Integer(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();
}
}
Output:
C:\java> javac VectorDemo.java
C:\java> java VectorDemo
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
The Stack
The Stack class
implements a last-in-first-out (LIFO) stack of elements. We can think of a
stack literally as a vertical stack of objects; when you add a new element, it
gets stacked on top of the others. When you pull an element off the stack, it
comes off the top. In other words, the last element you added to the stack is
the first one to come back off. 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.
Stack( )
Methods inherited from its parent class
Vector, Stack defines following methods:
SN
|
Methods with
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 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. |
Prog. No.:- 94 (Stack interface)
import java.util.*;
public class StackDemo {
static void showpush(Stack st, int a) {
st.push(new Integer(a));
System.out.println("push(" + a + ")");
System.out.println("stack: " + st);
}
static void showpop(Stack st) {
System.out.print("pop -> ");
Integer a = (Integer) st.pop();
System.out.println(a);
System.out.println("stack: " + st);
}
public static void main(String args[]) {
Stack st = new Stack();
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");
}
}
}
Output:
C:\java> javac StackDemo.java
C:\java> java StackDemo
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
The Dictionary
The Dictionary
class is an abstract class that defines a data structure for mapping keys to
values. This is useful in cases where you want to be able to access data via a
particular key rather than an integer index. Since the Dictionary class is
abstract, it provides only the framework for a key-mapped data structure rather
than a specific implementation. Dictionary is an abstract class that represents
a key/value storage repository and operates much like Map.
Given a key and
value, you can store the value in a Dictionary object. Once the value is
stored, you can retrieve it by using its key. Thus, like a map, a dictionary
can be thought of as a list of key/value pairs.
The abstract methods defined by Dictionary
are listed below:
SN
|
Methods with
Description
|
1
|
Enumeration elements( )
Returns an enumeration of the values contained in the dictionary. |
2
|
Object get(Object key)
Returns the object that contains the value associated with key. If key is not in the dictionary, a null object is returned. |
3
|
boolean isEmpty( )
Returns true if the dictionary is empty, and returns false if it contains at least one key. |
4
|
Enumeration keys( )
Returns an enumeration of the keys contained in the dictionary. |
5
|
Object put(Object key, Object value)
Inserts a key and its value into the dictionary. Returns null if key is not already in the dictionary; returns the previous value associated with key if key is already in the dictionary. |
6
|
Object remove(Object key)
Removes key and its value. Returns the value associated with key. If key is not in the dictionary, a null is returned. |
7
|
int size( )
Returns the number of entries in the dictionary. |
The Dictionary
class is obsolete. We should implement the Map interface to
obtain key/value storage functionality. The Map interface maps unique keys to
values. A key is an object that you use to retrieve a value at a later date.
·
Given a key and a value, you can store the value
in a Map object. After the value is stored, you can retrieve it by using its
key.
·
Several methods throw a NoSuchElementException
when no items exist in the invoking map.
·
A ClassCastException is thrown when an object is
incompatible with the elements in a map.
·
A ClassCastException is thrown when an object is
incompatible with the elements in a map.
·
A NullPointerException is thrown if an attempt
is made to use a null object and null is not allowed in the map.
·
An UnsupportedOperationException is thrown when
an attempt is made to change an unmodifiable map.
SN
|
Methods with
Description
|
1
|
void clear( )
Removes all key/value pairs from the invoking map. |
2
|
boolean containsKey(Object k)
Returns true if the invoking map contains k as a key. Otherwise, returns false. |
3
|
boolean containsValue(Object v)
Returns true if the map contains v as a value. Otherwise, returns false. |
4
|
Set entrySet( )
Returns a Set that contains the entries in the map. The set contains objects of type Map.Entry. This method provides a set-view of the invoking map. |
5
|
boolean equals(Object obj)
Returns true if obj is a Map and contains the same entries. Otherwise, returns false. |
6
|
Object get(Object k)
Returns the value associated with the key k. |
7
|
int hashCode( )
Returns the hash code for the invoking map. |
8
|
boolean isEmpty( )
Returns true if the invoking map is empty. Otherwise, returns false. |
9
|
Set keySet( )
Returns a Set that contains the keys in the invoking map. This method provides a set-view of the keys in the invoking map. |
10
|
Object put(Object k, Object v)
Puts an entry in the invoking map, overwriting any previous value associated with the key. The key and value are k and v, respectively. Returns null if the key did not already exist. Otherwise, the previous value linked to the key is returned. |
11
|
void putAll(Map m)
Puts all the entries from m into this map. |
12
|
Object remove(Object k)
Removes the entry whose key equals k. |
13
|
int size( )
Returns the number of key/value pairs in the map. |
14
|
Collection values( )
Returns a collection containing the values in the map. This method provides a collection-view of the values in the map. |
Prog. No.:- 95
import java.util.*;
public class CollectionsDemo {
public static void main(String[] args) {
Map m1 = new HashMap();
m1.put("Aarti", "8");
m1.put("Sunil", "31");
m1.put("Ayan", "12");
m1.put("Amit", "14");
System.out.println();
System.out.println(" Map Elements");
System.out.print("\t" + m1);
}
}
Output:
C:\java> javac CollectionsDemo.java
C:\java> java CollectionsDemo
Map Elements
{Sunil=31, Ayan=12, Amit=14, Aarti=8}
The Hashtable
The Hashtable
class provides a means of organizing data based on some user-defined key
structure. For example, in an address list hash table you could store and sort
data based on a key such as ZIP code rather than on a person's name. The
specific meaning of keys in regard to hash tables is totally dependent on the
usage of the hash table and the data it contains. Hashtable was part of the
original java.util and is a concrete implementation of a Dictionary.
However, 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.
The Hashtable defines four constructors.
The first version is the default
constructor:
Hashtable( )
The second version creates a hash table
that has an initial size specified by size:
Hashtable(int size)
The third version 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.
Hashtable(int size, float fillRatio)
The fourth version creates a hash table
that is initialized with the elements in m. The capacity of the hash table is
set to twice the number of elements in m. The default load factor of 0.75 is
used.
Hashtable(Map m)
Methods defined by Map interface, Hashtable
defines the following methods:
SN
|
Methods with
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 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 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 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 key. If 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 key isn't already in the hash table; returns the previous value associated with key if 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 key and its value. Returns the value associated with key. If 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. |
Prog. No.:- 96 (HashTable
interface)
import java.util.*;
public class HashTableDemo {
public static void main(String args[]) {
// Create a hash map
Hashtable balance = new Hashtable();
Enumeration names;
String str;
double bal;
balance.put("Aarti", new Double(3434.34));
balance.put("Sunil", new Double(123.22));
balance.put("Ayan", new Double(1378.00));
balance.put("Amit", new Double(99.22));
balance.put("Ashok", new Double(-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 Aarti's account
bal = ((Double)balance.get("Aarti")).doubleValue();
balance.put("Aarti", new Double(bal+1000));
System.out.println("Aarti's new balance: " +
balance.get("Aarti"));
}
}
Output:
C:\java> javac HashTableDemo.java
C:\java> java HashTableDemo
Ashok: -19.08
Aarti: 3434.34
Sunil: 123.22
Amit: 99.22
Ayan: 1378.0
Aarti's new balance: 4434.34
The 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. 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 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.
Properties defaults;
The Properties define two constructors. The
first version creates a Properties object that has no default values:
Properties( )
The second creates an object that uses
propDefault for its default values. In both cases, the property list is empty:
Properties(Properties propDefault)
Methods defined by Hashtable, Properties
define the following methods:
SN
|
Methods with
Description
|
1
|
String getProperty(String key)
Returns the value associated with key. A null object is returned if key is neither in the list nor in the default property list. |
2
|
String getProperty(String key, String defaultProperty)
Returns the value associated with key. defaultProperty is returned if key is neither in the list nor in the default property list. |
3
|
void list(PrintStream streamOut)
Sends the property list to the output stream linked to streamOut. |
4
|
void list(PrintWriter streamOut)
Sends the property list to the output stream linked to streamOut. |
5
|
void load(InputStream streamIn) 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 key. Returns the previous value associated with key, or returns null if no such association exists. |
8
|
void store(OutputStream streamOut, String description)
After writing the string specified by description, the property list is written to the output stream linked to streamOut. |
Prog. No.:- 97 (Properties
interface)
import java.util.*;
public class PropDemo {
public static void main(String args[]) {
Properties capitals = new Properties();
Set states;
String str;
capitals.put("Delhi", "Delhi");
capitals.put("Himachal", "Shimla");
capitals.put("Punjab", "Chandigrah");
capitals.put("J&K", "Srinagar");
// 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("Gujraat", "Not Found");
System.out.println("The capital of Florida is "
+ str + ".");
}
}
Output:
C:\java> javac PropDemo.java
C:\java> java PropDemo
The capital of Delhi is Delhi.
The capital of Himachal is Shimla.
The capital of Punjab is chandigrah.
The capital of J&K is Srinagar.
The capital of Gujraat is Not Found.
Applet
An
applet is a small Java program that is embedded and ran in some other Java
interpreter program such as :A Java technology-enabled browser. Sun’s applet
viewer program called appletviewer. A mini-application, Distributed along with
Web pages and run under an applet viewer. An applet is a Java program that runs
in a Web browser. An applet can be a fully functional Java application because
it has the entire Java API at its disposal.
There are some important differences between an applet and a
standalone Java application, including the following:
Ø An applet is a Java class that extends the
java.applet.Applet class.
Ø A main() method is not invoked on an applet, and an applet
class will not define main().
Ø Applets are designed to be embedded within an HTML page.
Ø When a user views an HTML page that contains an applet, the
code for the applet is downloaded to the user's machine.
Ø A JVM is required to view an applet. The JVM can be either a
plug-in of the Web browser or a separate runtime environment.
Ø The JVM on the user's machine creates an instance of the
applet class and invokes various methods during the applet's lifetime.
Ø Applets have strict security rules that are enforced by the
Web browser. The security of an applet is often referred to as sandbox
security, comparing the applet to a child playing in a sandbox with various
rules that must be followed.
Ø Other classes that the applet needs can be downloaded in a
single Java Archive (JAR) file.
Ø Applets are invoked differently
Ø Applets are subject
to more security constraints
Ø Applets do not have
constructors
Ø Initializations are
done in method init
Ø Applets are
themselves containers in a window
Ø Applets must be
explicitly derived from class Applet or JApplet
Life
Cycle of an Applet:
Four methods in the Applet class give you the framework on
which we build any applet:
- init: This method is intended for whatever initialization is needed for your applet. It is called after the param tags inside the applet tag have been processed.
- start: This method is automatically called after the browser calls the init method. It is also called whenever the user returns to the page containing the applet after having gone off to other pages.
- stop: This method is automatically called when the user moves off the page on which the applet sits. It can, therefore, be called repeatedly in the same applet.
- destroy: This method is only called when the browser shuts down normally. Because applets are meant to live on an HTML page, you should not normally leave resources behind after a user leaves the page that contains the applet.
- paint: Invoked immediately after the start() method, and also any time the applet needs to repaint itself in the browser. The paint() method is actually inherited from the java.awt.
A
"Hello, World" Applet:
The following is a simple applet named
HelloWorldApplet.java:
Prog. No.:- 98
import java.applet.*;
import java.awt.*;
public class HelloWorldApplet
extends Applet
{
public void paint (Graphics g)
{
g.drawString ("Hello World", 25, 50);
}
}
These import statements bring the
classes into the scope of our applet class:
- java.applet.Applet.
- java.awt.Graphics.
Without those import statements, the
Java compiler would not recognize the classes Applet and Graphics, which the
applet class refers to.
The
Applet CLASS:
Every applet is an extension of the java.applet.Applet
class. The base Applet class provides methods that a derived Applet class
may call to obtain information and services from the browser context.
These include methods that do the following:
- Get applet parameters
- Get the network location of the HTML file that contains the applet
- Get the network location of the applet class directory
- Print a status message in the browser
- Fetch an image
- Fetch an audio clip
- Play an audio clip
- Resize the applet
Additionally, the Applet class
provides an interface by which the viewer or browser obtains information about
the applet and controls the applet's execution. The viewer may:
- request information about the author, version and copyright of the applet
- request a description of the parameters the applet recognizes
- initialize the applet
- destroy the applet
- start the applet's execution
- stop the applet's execution
The Applet class provides default
implementations of each of these methods. Those implementations may be
overridden as necessary.
The "Hello, World" applet
is complete as it stands. The only method overridden is the paint method.
Invoking
an Applet:
An applet may be invoked by
embedding directives in an HTML file and viewing the file through an applet
viewer or Java-enabled browser.
The <applet> tag is the basis
for embedding an applet in an HTML file. Below is an example that invokes the
"Hello, World" applet:
<html>
<title>The Hello, World
Applet</title>
<hr>
<applet
code="HelloWorldApplet.class" width="320"
height="120">
If your browser was Java-enabled, a
"Hello, World"
message would appear here.
</applet>
<hr>
</html>
The code attribute of the
<applet> tag is required. It specifies the Applet class to run. Width and
height are also required to specify the initial size of the panel in which an
applet runs. The applet directive must be closed with a </applet> tag.
If an applet takes parameters,
values may be passed for the parameters by adding <param> tags between
<applet> and </applet>. The browser ignores text and other tags
between the applet tags.
Non-Java-enabled browsers do not
process <applet> and </applet>. Therefore, anything that appears
between the tags, not related to the applet, is visible in non-Java-enabled
browsers.
The viewer or browser looks for the
compiled Java code at the location of the document. To specify otherwise, use
the codebase attribute of the <applet> tag as shown:
<applet
codebase="http://amrood.com/applets"
code="HelloWorldApplet.class"
width="320" height="120">
If an applet resides in a package
other than the default, the holding package must be specified in the code
attribute using the period character (.) to separate package/class components.
For example:
<applet
code="mypackage.subpackage.TestApplet.class"
width="320"
height="120">
Getting
Applet Parameters:
The following example demonstrates
how to make an applet respond to setup parameters specified in the document.
This applet displays a checkerboard pattern of black and a second color.
The second color and the size of
each square may be specified as parameters to the applet within the document.
CheckerApplet gets its parameters in
the init() method. It may also get its parameters in the paint() method.
However, getting the values and saving the settings once at the start of the
applet, instead of at every refresh, is convenient and efficient.
The applet viewer or browser calls
the init() method of each applet it runs. The viewer calls init() once,
immediately after loading the applet. (Applet.init() is implemented to do
nothing.) Override the default implementation to insert custom initialization
code.
The Applet.getParameter() method
fetches a parameter given the parameter's name (the value of a parameter is
always a string). If the value is numeric or other non-character data, the
string must be parsed.
The following is a skeleton of
CheckerApplet.java:
import
java.applet.*;
import
java.awt.*;
public
class CheckerApplet extends Applet
{
int squareSize = 50;// initialized to
default size
public void init () {}
private void parseSquareSize (String param)
{}
private Color parseColor (String param) {}
public void paint (Graphics g) {}
}
Here are CheckerApplet's init() and
private parseSquareSize() methods:
public
void init ()
{
String squareSizeParam = getParameter
("squareSize");
parseSquareSize (squareSizeParam);
String colorParam = getParameter
("color");
Color fg = parseColor (colorParam);
setBackground (Color.black);
setForeground (fg);
}
private
void parseSquareSize (String param)
{
if (param == null) return;
try {
squareSize = Integer.parseInt (param);
}
catch (Exception e) {
// Let default value remain
}
}
The applet calls parseSquareSize()
to parse the squareSize parameter. parseSquareSize() calls the library method
Integer.parseInt(), which parses a string and returns an integer.
Integer.parseInt() throws an exception whenever its argument is invalid.
Therefore, parseSquareSize() catches
exceptions, rather than allowing the applet to fail on bad input.
The applet calls parseColor() to
parse the color parameter into a Color value. parseColor() does a series of
string comparisons to match the parameter value to the name of a predefined
color. You need to implement these methods to make this applet works.
Specifying
Applet Parameters:
The following is an example of an
HTML file with a CheckerApplet embedded in it. The HTML file specifies both
parameters to the applet by means of the <param> tag.
<html>
<title>Checkerboard
Applet</title>
<hr>
<applet
code="CheckerApplet.class" width="480"
height="320">
<param
name="color" value="blue">
<param
name="squaresize" value="30">
</applet>
<hr>
</html>
Note: Parameter names are not case sensitive.
Application
Conversion to Applets:
It is easy to convert a graphical
Java application (that is, an application that uses the AWT and that you can
start with the java program launcher) into an applet that you can embed in a
web page.
Here are the specific steps for converting an application to
an applet.
- Make an HTML page with the appropriate tag to load the applet code.
- Supply a subclass of the JApplet class. Make this class public. Otherwise, the applet cannot be loaded.
- Eliminate the main method in the application. Do not construct a frame window for the application. Your application will be displayed inside the browser.
- Move any initialization code from the frame window constructor to the init method of the applet. You don't need to explicitly construct the applet object.the browser instantiates it for you and calls the init method.
- Remove the call to setSize; for applets, sizing is done with the width and height parameters in the HTML file.
- Remove the call to setDefaultCloseOperation. An applet cannot be closed; it terminates when the browser exits.
- If the application calls setTitle, eliminate the call to the method. Applets cannot have title bars. (You can, of course, title the web page itself, using the HTML title tag.)
- Don't call setVisible(true). The applet is displayed automatically.
Event
Handling:
Applets inherit a group of
event-handling methods from the Container class. The Container class defines
several methods, such as processKeyEvent and processMouseEvent, for handling
particular types of events, and then one catch-all method called processEvent.
Prog. No.:- 99
import java.awt.event.MouseListener;
import java.awt.event.MouseEvent;
import java.applet.Applet;
import java.awt.Graphics;
public class ExampleEventHandling
extends Applet
implements MouseListener {
StringBuffer strBuffer;
public void init() {
addMouseListener(this);
strBuffer
= new StringBuffer();
addItem("initializing the apple
");
}
public void start() {
addItem("starting the applet
");
}
public void stop() {
addItem("stopping the applet
");
}
public void destroy() {
addItem("unloading the
applet");
}
void addItem(String word) {
System.out.println(word);
strBuffer.append(word);
repaint();
}
public void paint(Graphics g) {
//Draw
a Rectangle around the applet's display area.
g.drawRect(0, 0,
getWidth() - 1,
getHeight() - 1);
//display
the string inside the rectangle.
g.drawString(strBuffer.toString(), 10,
20);
}
public void mouseEntered(MouseEvent event) {
}
public void mouseExited(MouseEvent event) {
}
public void mousePressed(MouseEvent event) {
}
public void mouseReleased(MouseEvent event) {
}
public void mouseClicked(MouseEvent event) {
addItem("mouse
clicked! ");
}
}
Now, let us call this applet as
follows:
<html>
<title>Event
Handling</title>
<hr>
<applet
code="ExampleEventHandling.class"
width="300"
height="300">
</applet>
<hr>
</html>
Initially, the applet will display
"initializing the applet. Starting the applet." Then once you click
inside the rectangle "mouse clicked" will be displayed as well.
Displaying
Images:
An applet can display images of the
format GIF, JPEG, BMP, and others. To display an image within the applet, you
use the drawImage() method found in the java.awt.Graphics class.
Following is the example showing all the steps to show
images:
Prog. No.:- 100
import java.applet.*;
import java.awt.*;
import java.net.*;
public class ImageDemo extends
Applet
{
private Image image;
private AppletContext context;
public void init()
{
context = this.getAppletContext();
String imageURL = this.getParameter("image");
if(imageURL == null)
{
imageURL = "java.jpg";
}
try
{
URL url = new
URL(this.getDocumentBase(), imageURL);
image = context.getImage(url);
}catch(MalformedURLException e)
{
e.printStackTrace();
// Display in browser status bar
context.showStatus("Could not
load image!");
}
}
public void paint(Graphics g)
{
context.showStatus("Displaying image");
g.drawImage(image, 0, 0, 200, 84, null);
g.drawString("www.javalicense.com", 35, 100);
}
}
Now, let us call this applet as follows:
<html>
<title>The ImageDemo
applet</title>
<hr>
<applet
code="ImageDemo.class" width="300"
height="200">
<param name="image"
value="java.jpg">
</applet>
<hr>
</html>
Playing
Audio:
An applet can play an audio file
represented by the AudioClip interface in the java.applet package. The
AudioClip interface has three methods, including:
- public void play(): Plays the audio clip one time, from the beginning.
- public void loop(): Causes the audio clip to replay continually.
- public void stop(): Stops playing the audio clip.
To obtain an AudioClip object, you
must invoke the getAudioClip() method of the Applet class. The getAudioClip()
method returns immediately, whether or not the URL resolves to an actual audio
file. The audio file is not downloaded until an attempt is made to play the
audio clip.
Following is the example showing all the steps to play an
audio:
Prog. No.:- 101
import java.applet.*;
import java.awt.*;
import java.net.*;
public class AudioDemo extends
Applet
{
private AudioClip clip;
private AppletContext context;
public void init()
{
context = this.getAppletContext();
String audioURL = this.getParameter("audio");
if(audioURL == null)
{
audioURL = "default.au";
}
try
{
URL url = new
URL(this.getDocumentBase(), audioURL);
clip = context.getAudioClip(url);
}catch(MalformedURLException e)
{
e.printStackTrace();
context.showStatus("Could not
load audio file!");
}
}
public void start()
{
if(clip != null)
{
clip.loop();
}
}
public void stop()
{
if(clip != null)
{
clip.stop();
}
}
}
Now, let us call this applet as follows:
<html>
<title>The ImageDemo
applet</title>
<hr>
<applet
code="ImageDemo.class" width="0" height="0">
<param name="audio"
value="test.wav">
</applet>
<hr>
</html>
Comments
Post a Comment