Showing posts with label JAVA Data Structures. Show all posts
Showing posts with label JAVA Data Structures. Show all posts

Saturday, 24 August 2013

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 defines the following instance variable. This variable holds a default property list associated with a Properties object.
Properties defaults;
The Properties defines 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)
Apart from the methods defined by Hashtable, Properties defines following methods:
SNMethods with Description
1String 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.
2String 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.
3void list(PrintStream streamOut)
Sends the property list to the output stream linked to streamOut.
4void list(PrintWriter streamOut)
Sends the property list to the output stream linked to streamOut.
5void load(InputStream streamIn) throws IOException
Inputs a property list from the input stream linked to streamIn.
6Enumeration propertyNames( )
Returns an enumeration of the keys. This includes those keys found in the default property list, too.
7Object setProperty(String key, String value)
Associates value with key. Returns the previous value associated with key, or returns null if no such association exists.
8void store(OutputStream streamOut, 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 would produce following result:
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 - The Hashtable Class

Hashtable was part of the original java.util and is a concrete implementation of a Dictionary.
However, Java 2 reengineered 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)
Apart from the methods defined by Map interface, Hashtable defines following methods:
SNMethods with Description
1void clear( )
Resets and empties the hash table.
2Object clone( )
Returns a duplicate of the invoking object.
3boolean contains(Object value)
Returns true if some value equal to value exists within the hash table. Returns false if the value isn't found.
4boolean containsKey(Object key)
Returns true if some key equal to key exists within the hash table. Returns false if the key isn't found.
5boolean containsValue(Object value)
Returns true if some value equal to value exists within the hash table. Returns false if the value isn't found.
6Enumeration elements( )
Returns an enumeration of the values contained in the hash table.
7Object 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.
8boolean isEmpty( )
Returns true if the hash table is empty; returns false if it contains at least one key.
9Enumeration keys( )
Returns an enumeration of the keys contained in the hash table.
10Object 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.
11void rehash( )
Increases the size of the hash table and rehashes all of its keys.
12Object 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.
13int size( )
Returns the number of entries in the hash table.
14String 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;
      double bal;

      balance.put("Zara", new Double(3434.34));
      balance.put("Mahnaz", new Double(123.22));
      balance.put("Ayan", new Double(1378.00));
      balance.put("Daisy", new Double(99.22));
      balance.put("Qadir", 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 Zara's account
      bal = ((Double)balance.get("Zara")).doubleValue();
      balance.put("Zara", new Double(bal+1000));
      System.out.println("Zara's new balance: " +
      balance.get("Zara"));
   }
}
This would produce following result:
Qadir: -19.08
Zara: 3434.34
Mahnaz: 123.22
Daisy: 99.22
Ayan: 1378.0

Zara's new balance: 4434.34

Java - The Dictionary Class

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:
SNMethods with Description
1Enumeration elements( )
Returns an enumeration of the values contained in the dictionary.
2Object 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.
3boolean isEmpty( )
Returns true if the dictionary is empty, and returns false if it contains at least one key.
4Enumeration keys( )
Returns an enumeration of the keys contained in the dictionary.
5Object 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.
6Object 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.
7int size( )
Returns the number of entries in the dictionary.
The Dictionary class is obsolete. You should implement the Map interface to obtain key/value storage functionality.

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.
Stack( )
Apart from the methods inherited from its parent class Vector, Stack defines following methods:
SNMethods with Description
1boolean empty() 
Tests if this stack is empty. Returns true if the stack is empty, and returns false if the stack contains elements.
2Object peek( )
Returns the element on the top of the stack, but does not remove it.
3Object pop( )
Returns the element on the top of the stack, removing it in the process.
4Object push(Object element)
Pushes element onto the stack. element is also returned.
5int 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(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");
      }
   }
}
This would produce following result:
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 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.
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)
Apart from the methods inherited from its parent classes, Vector defines following methods:
SNMethods with Description
1void add(int index, Object element) 
Inserts the specified element at the specified position in this Vector.
2boolean add(Object o) 
Appends the specified element to the end of this Vector.
3boolean 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.
4boolean addAll(int index, Collection c) 
Inserts all of the elements in in the specified Collection into this Vector at the specified position.
5void addElement(Object obj) 
Adds the specified component to the end of this vector, increasing its size by one.
6int capacity() 
Returns the current capacity of this vector.
7void clear() 
Removes all of the elements from this Vector.
8Object clone() 
Returns a clone of this vector.
9boolean contains(Object elem) 
Tests if the specified object is a component in this vector.
10boolean containsAll(Collection c) 
Returns true if this Vector contains all of the elements in the specified Collection.
11void copyInto(Object[] anArray) 
Copies the components of this vector into the specified array.
12Object elementAt(int index) 
Returns the component at the specified index.
13Enumeration elements() 
Returns an enumeration of the components of this vector.
14void 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.
15boolean equals(Object o) 
Compares the specified Object with this Vector for equality.
16Object firstElement() 
Returns the first component (the item at index 0) of this vector.
17Object get(int index) 
Returns the element at the specified position in this Vector.
18int hashCode() 
Returns the hash code value for this Vector.
19int indexOf(Object elem) 
Searches for the first occurence of the given argument, testing for equality using the equals method.
20int 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.
21void insertElementAt(Object obj, int index) 
Inserts the specified object as a component in this vector at the specified index.
22boolean isEmpty() 
Tests if this vector has no components.
23Object lastElement() 
Returns the last component of the vector.
24int lastIndexOf(Object elem) 
Returns the index of the last occurrence of the specified object in this vector.
25int lastIndexOf(Object elem, int index) 
Searches backwards for the specified object, starting from the specified index, and returns an index to it.
26Object remove(int index) 
Removes the element at the specified position in this Vector.
27boolean 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.
28boolean removeAll(Collection c) 
Removes from this Vector all of its elements that are contained in the specified Collection.
29void removeAllElements() 
Removes all components from this vector and sets its size to zero.
30boolean removeElement(Object obj) 
Removes the first (lowest-indexed) occurrence of the argument from this vector.
31void removeElementAt(int index) 
removeElementAt(int index)
32protected void removeRange(int fromIndex, int toIndex)
Removes from this List all of the elements whose index is between fromIndex, inclusive and toIndex, exclusive.
33boolean retainAll(Collection c) 
Retains only the elements in this Vector that are contained in the specified Collection.
34Object set(int index, Object element)
Replaces the element at the specified position in this Vector with the specified element.
35void setElementAt(Object obj, int index) 
Sets the component at the specified index of this vector to be the specified object.
36void setSize(int newSize) 
Sets the size of this vector.
37int size() 
Returns the number of components in this vector.
38List subList(int fromIndex, int toIndex) 
Returns a view of the portion of this List between fromIndex, inclusive, and toIndex, exclusive.
39Object[] toArray()
Returns an array containing all of the elements in this Vector in the correct order.
40Object[] 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.
41String toString() 
Returns a string representation of this Vector, containing the String representation of each element.
42void 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(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();
   }
}
This would produce following result:
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