Java tutorial 7

19. 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.

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:

SN 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.

Example:

Following is the example showing usage of Enumeration.

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()); 
      }
   }
}

This would produce the following result:

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:

Example:

The following program illustrates several of the methods supported by this data structure:

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);


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)

Example:

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

Vector<Object> v = new Vector<Object>(3, 2);
System.out.println("Initial size: " + v.size());
System.out.println("Initial capacity: " + v.capacity());
v.addElement(1);
v.addElement(1.2);
v.addElement(new Integer(3));
v.addElement(new Double(4.5));
System.out.println("New size: " + v.size());
System.out.println("New capacity: " + v.capacity());
System.out.println("The first element is: " + v.firstElement());
System.out.println("The last element is: " + v.lastElement());

Enumeration vEnum = v.elements();
System.out.println("Elements in vector: ");
while(vEnum.hasMoreElements())
{
System.out.println(vEnum.nextElement());
}


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:

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.

Example:

private Stack st;

private static <E> void showPush(Stack<E> st, E a)
{
st.push(a);
System.out.println("push ( " + a + " )");
System.out.println("Stack: " + st);
}
private static <E> void showPop(Stack<E> st)
{
System.out.println("pop - > " + st.pop());
System.out.println("Stack: " + st);
}

@SuppressWarnings("unchecked")
public static void main(String[] args) {
@SuppressWarnings("rawtypes")
Stack st = new Stack();
System.out.println("New Stack: " + st);
showPush(st, 42.2);
showPush(st, 66);
showPush(st, "STR");
showPop(st);
showPop(st);
showPop(st);

try {
showPop(st);
} catch (EmptyStackException e) {
System.out.println("Empty Stack exception.");
}
}


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. You 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 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.

Example:

Map has its implementation in various classes like HashMap. Following is the example to explain map 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 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.


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)

Apart from the 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.

Example:

The following program illustrates several of the methods supported by this data structure:

// Create a Hash table
Hashtable<String, Double> balance = new Hashtable<String, Double>();
Enumeration<String> names;
balance.put("Zara", 3434.34);
balance.put("Mahnaz", 123.22);
balance.put("Ayan", 1378.00);
balance.put("Paisy", 99.22);

// Show all balance in Hash table
names = balance.keys();
while(names.hasMoreElements())
{
Object str = names.nextElement();
System.out.println(str + " has a balance of " + balance.get(str));
}
System.out.println();
// Deposit 1,000 into Zara's account
double value;
value = ((Double) balance.get("Zara")).doubleValue() + 1000.0;
balance.put("Zara", new Double(value));
System.out.println("Zara's new balance: " + balance.get("Zara"));

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)

Apart from the 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

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 + ".");









评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值