Reading:  

Quick walk through the advanced concepts in Java - Part 3 of series


Working with Data Structures

The data structures given by the Java utility package are powerful and perform a huge range of functions. It consists of the following classes and interface:

  • Vector
  • BitSet
  • Enumeration
  • Stack
  • Hashtable
  • Dictionary
  • Properties

These classes are old now anda new framework called Collections Frameworkhas introduced in Java-2.

Vector:

The Vector class is same as Java array, except that it can grow as necessary to accommodate new elements.Vectorelement object accessed via an index into the vector. When necessary it shrinks and grows automatically.

Vector Methods:                                               

  • boolean addAll(Collection o)
    Appends the elements in the Collection specified end of this Vector and are returned by the Collection's Iterator specified.
  • boolean addAll(intindexNum, Collection o)
    Inserts the elements in the Collection specified into theVector at the position specified.
  • void addElement(Object obj)
    Adds the component specified to the end of the vector, its size increased by one.
  • boolean add(Object a)
    To the end of the Vector appends the element specified.
  • void add(int index, Object element)
    Inserts the element specified at the position specified in Vector.
  • void clear()
    Removes all of the elements from Vector.
  • int capacity()
    to get the current capacity of vector.
  • boolean contains(Object o)
    Tests if the object specified is a component in vector.
  • Object clone()
    Returns a clone of this vector.
  • voidcopyInto(Object[] objArray)
    Copies the vector components into specified array.
  • booleancontainsAll(Collection a)
    Returns true if this Vector contains all of elements in Collection specified.
  • boolean equals(Object b)
    The specified Object compares with Vector for equality.
  • void ensureCapacity(intcapmin)
    if necessary increases the capacity of vector.
  • Enumeration elements()
    Returns an enumeration of the vector components.
  • Object elementAt(int d)
    Returns the component at specified index.
  • Object firstElement()
    Returns the component at index 0(i.e. first element) of vector.
  • Object lastElement()
    Returns the vector last component of vector.
  • int hashCode()
    Returns the hash code value.
  • Object get(int c)
    Returns the element at the specified position in Vector.
  • boolean isEmpty()
    To check if the vector has no components.
  • int lastIndexOf(Object e)
    Returns the index of the last occurrence of object specified in vector.
  • Object remove(inti)
    Removes the element at the specified position in Vector.
  • int indexOf(Object e, inti)
    Searches for the first occurrence of the given argument, beginning the search at index, and testing for equality using the equals method.
  • booleanremoveElement(Object o)
    Removes the first at index 0 occurrence of the argument from vector.
  • booleanretainAll(Collection a)
    Retains only the Vector elements that are contained in Collection specified.
  • protected void removeRange(intfromIndex, inttoIndex)
    Removes the elements where the elements are between given index
  • Object set(inti, Object e)
    Replaces the element at the position specified in the Vector with element specified.
  • int size()
    to get the number of components in vector.
  • Object[] toArray()
    To get an array containing the elements in the Vector in correct order.
  • void trimToSize()
    Trims the vector's current size.
  • String toString()
    Contains the String representation of each element and returns a string representation of the Vector

 

Example for Vector:

import java.util.Vector;
public class PracticeCollectionVector {
	public static void main(String[] args) {
		Vector vct = new Vector();
		vct.add(10);
		vct.add(20);
		vct.add("vector string");
		System.out.println(vct);
		System.out.println("vector value :" + vct.get(2));
		System.out.println("vector first element :" + vct.firstElement());
		vct.add(0, 9);
		System.out.println(vct);
		System.out.println("vector is emplty :" + vct.isEmpty());
	}
}

Output

BitSet:

The BitSet class is useful in cases where to keep up with a set of Boolean values. Assign a bit tovalue and clear or set it as appropriate.

ABitSet class creates a type of array that stores bit values. When necessary it shrinks and grows automatically.

BitSet Methods:

  • void clear( ): All bits will be zero.
  • void and(BitSetbitSet): contents of invoking BitSet object with those specified by bitSet.
  • int cardinality( ): Returns number of set bits in invoking object.
  • void clear(inti): Bit will be zero specified by index.
  • boolean equals(Object bitSet): Returns true if invoking bit set is equivalent to the passed in bitSet or else returns false.
  • Object clone( )
    the invoking BitSet object will be duplicated.
  • boolean get(int index)
    Returns current state of the bit at specified index.
  • int hashCode( )
    Returns hash code for invoking object.
  • boolean isEmpty( )
    Returns true if all bits in invoking object are zero.
  • void set(inti)
    Sets bit specified by index.
  • void flip(inti)
    the bit specified by index will be reversed.
  • void set(int start, int end)
    Sets bits from start to end.
  • String toString( )
    Returns string equivalent of invoking BitSet object.
  • boolean get(int index)
    Returns current state of bit at specified index.

Example for BitSet:

import java.util.BitSet;
public class ExampleBitSet {
	public static void main(String args[]) {
		BitSet b1 = new BitSet(10);
		BitSet b2 = new BitSet(10);

		// set some bits
		for (int i = 0; i < 10; i++) {
			if ((i % 2) == 0) b1.set(i);
			if ((i % 5) != 0) b2.set(i);
		}
		System.out.println("b1: ");
		System.out.println(b1);
		System.out.println("\nb2: ");
		System.out.println(b2);

		// OR bits
		b2.or(b1);
		System.out.println("\nb1 OR b2: ");
		System.out.println(b2);
	}
}

Output

b1: {0, 2, 4, 6, 8}
b2: {1, 2, 3, 4, 6, 7, 8, 9}
b1 OR b2: {0, 1, 2, 3, 4, 6, 7, 8, 9}

 

Enumeration:

Enumerationprovides iterative access the each elements of an associated data structure, exactlyonce. It is very important within context of other data structures which is used to retrieve successive elements from a data structure. 

Enumeration Methods:

  • Object nextElement( )
    Returns the next object in enumeration as a generic Object reference.
  • boolean hasMoreElements( )
    Returns true when there are elements to extract or else returns false.

Example for Enumerations:

import java.util.Enumeration;
import java.util.Vector;

public class ExampleEnumerations {
	public static void main(String args[]) {
		Vector < String > v = new Vector < String > ();
		v.add("Hello");
		v.add("Enumerations");

		Enumeration < String > e = (Enumeration < String > ) v.elements();
		while (e.hasMoreElements()) {
			System.out.print(e.nextElement() + " ");
		}
		System.out.println();
	}
}

Output

Stack:

The Stack class follow LIFO (last-in-first-out) style that is last element added to stack is first one to come out. Whereuser addsan element it will be on the top of stack.

Stack Methods:

  • boolean empty()
    verifies if this stack is empty returns true or else returns false.
  • Object push(Object element)
    Adds element onto stack and also is returned element.
  • Object peek( )
    The element on the stack top is returned, but does not delete the element.
  • int search(Object element)
    Searches for element in the stack. If found, its offset from the top of stack is returned. Or else returns -1.
  • Enumeration elements()
    Returns an enumeration of stack components.

Example for Stack:

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

		Stack st = new Stack();

		//add elements to stack
		st.push("Java");
		st.push("Collection");
		st.push("Stack");

		System.out.println("\n" + "stack items are: " + st + "\n");
		System.out.println("-----------------------" + "\n");

		System.out.println("removing element from stack using pop: " + st.pop() + "\n");

		System.out.println("returning the top element using peek: " + stack.peek() + "\n");
	}
}

Output

Hashtable:

The Hashtable class is for data organizing based on user-defined key structure.

The meaning of keys in regard to hash tables is dependent on the usage of the hash table and its data.

Hashtable methods:

  • boolean containsKey(Object k)
    Returns true if key equal to key exists within the hash table or else returns false.
  • Object put(Object key, Object value)
    To inserts a key and a value into the hash table.
  • Object get(Object k)
    Returns object that contains the associated value ofkey or else return null.
  • void rehash( )
  • The size of the hash table increases and rehashes all keys.
  • boolean isEmpty()
    To check if thehashtable has no components.
  • Enumeration elements()
    Returns an enumeration of Hashtable components.
  • int size( )
    Returns the number of entries in hash table.

Example for Hashtable:

import java.util.Enumeration;
import java.util.Hashtable;

public classHashtableExample {
	public static void main(String[] args) {

		Hashtable has = new Hashtable();

		//add elements to hashtable
		has.put("Java", 23);
		has.put("Collection", 21);
		has.put("Hashtable", 25);

		System.out.println("\n" + "Hashtable items are: " + has + "\n");
		System.out.println("-----------------------" + "\n");

		String s1;

		Enumeration enu = has.keys();
		while (enu.hasMoreElements()) {

			s1 = (String) enu.nextElement();
			System.out.println(s1 + ": " + has.get(s1) + "\n");
		}
	}
}

Output

Dictionary:

The Dictionary class is an abstract class is useful to access data through a specific key and also defines a data structure for mapping keys to values.

The Dictionary class is obsolete. We need to implement the Map interface for dictionary class functionality.

Dictionary methods:

  • Object get(Object k)
    Returns the object that contains associated value of key or else return null.
  • Object remove(Object k)
    Returns the associated value with key. If key is not in dictionary, a null value is returned.
  • Object put(Object k, Object val)
    Adds a key and its value into dictionary.
  • Enumeration elements()
    Returns an enumeration of dictionary components.
  • boolean isEmpty()
    To check if the dictionary has no components.

 

Properties:

Properties is used to maintainthe values lists in which the key and value is a string.It is sub class of hashtable.

Properties methods:

  • Enumeration propertyNames( )
    Returns an enumeration of the keys and also default property list.
  • void store(OutputStreamstreamOut, String description)
    After writing string specified by description, the property list is written to output stream linked to streamOut.
  • void store(OutputStreamstreamOut, String description)
    once completed writing string as per the description specified, the property list is written to output stream linked to streamOut.
  • void list(PrintWriterstreamOut)
    The property list send to output stream linked to streamOut.
  • String getProperty(String key)
    Returns the associated value with key. If key is not in properties, a null value is returned.
  • void list(PrintStreamstreamOut)
    The property list send to output stream linked to streamOut.

Example:

import java.util.Iterator;
import java.util.Properties;
import java.util.Set;


public class PropertiesExample {
	public static void main(String args[]) {
		Properties pc = new Properties();
		Set country;
		String s1;

		pc.put("India", "New Delhi");
		pc.put("America", "Washington D.C");

		country = pc.keySet(); // get set-view of keys
		@SuppressWarnings("rawtypes")
		Iterator itr = country.iterator();
		while (itr.hasNext()) {
			s1 = (String) itr.next();
			System.out.println("The capital of " + s1 + " is " + pc.getProperty(s1));
			System.out.println("=====================================");
		}
	}
}

Output




Description

This is the last part in our tutorial series on Java. This tutorial is designed as a quick walk through the advanced concepts of Java Languages. This tutorial is subdivided into few chapters as shown below

  1. Data Structures
  2. Collections
  3. Generics
  4. Serialization
  5. Networking 
  6. Working with Emails
  7. Multithreading
  8. Getting started with Applets
  9. JavaDoc

Let us know if you find any issues with this tutorial. Also, if you can provide us with your feedback, that always help us improve.

 



Prerequisites

You must have read Part 1 and Part 2 of our tutorial series on Java.

Audience

Beginners or students looking to brush up their Java knowledge

Learning Objectives

To get an understanding on some of the advanced topics of Java.

Author: Subject Coach
Added on: 10th Mar 2015

You must be logged in as Student to ask a Question.

None just yet!