Friday, September 30, 2011

Java Collections Framework


A collection represents a group of objects, known as its elements. This framework is provided in the java.util package. Objects can be stored, retrieved, and manipulated as elements of collections. Collection is a Java Interface. Collections can be used in various scenarios like Storing phone numbers, Employee names database etc. They are basically used to group multiple elements into a single unit. Some collections allow duplicate elements while others do not. Some collections are ordered and others are not.

A Collections Framework mainly contains the following 3 parts
A Collections Framework is defined by a set of interfaces, concrete class implementations for most of the interfaces and a set of standard utility methods and algorithms. In addition, the framework also provides severalabstract implementations, which are designed to make it easier for you to create new and different implementations for handling collections of data.

Core Collection Interfaces

The core interfaces that define common functionality and allow collections to be manipulated independent of their implementation.
The 6 core Interfaces used in the Collection framework are:
  • Collection
  • Set
  • List
  • Iterator (Not a part of the Collections Framework)
  • SortedSet

  • Map
  • SortedMap
Note: Collection and Map are the two top-level interfaces.
Collection Interface

Map Interface
Concrete ClassesThe concrete classes that are specific implementations of the core interfaces, providing data structures that a java program can use.


Note: Concrete Classes for the Map is shown in the previous section.
Standard utility methods and algorithms
Standard utility methods and algorithms
that can be used to perform various operations on collections, such as sorting, searching or creating customizedcollections.

How are Collections Used

  • The collections stores object references, rather than objects themselves. Hence primitive values cannot be stored in a collection directly. They need to be encapsulated (using wrapper classes) into an Object prior tostoring them into a Collection (such as HashSet, HashMap etc).
  • The references are always stored as type Object. Thus, when you retrieve an element from a collection, you get an Object rather then the actual type of the collection stored in the database. Hence we need to downcast it to the Actual Type while retrieving an element from a collection.
  • One of the capabilities of the Collection Framework is to create a new Collection object and populate it with the contents of an existing Collection object of a same or different actual type.
Below is an example program showing the storing and retrieving of a few Collection Types
import java.util.*;

public class CollectionsDemo {

	public static void main(String[] args) {
		List a1 = new ArrayList();
		a1.add("Beginner");
		a1.add("Java");
		a1.add("tutorial");
		System.out.println(" ArrayList Elements");
		System.out.print("\t" + a1);
		List l1 = new LinkedList();
		l1.add("Beginner");
		l1.add("Java");
		l1.add("tutorial");
		System.out.println();
		System.out.println(" LinkedList Elements");
		System.out.print("\t" + l1);
		Set s1 = new HashSet(); // or new TreeSet() will order the elements;
		s1.add("Beginner");
		s1.add("Java");
		s1.add("Java");
		s1.add("tutorial");
		System.out.println();
		System.out.println(" Set Elements");
		System.out.print("\t" + s1);
		Map m1 = new HashMap(); // or new TreeMap() will order based on keys
		m1.put("Windows", "98");
		m1.put("Win", "XP");
		m1.put("Beginner", "Java");
		m1.put("Tutorial", "Site");
		System.out.println();
		System.out.println(" Map Elements");
		System.out.print("\t" + m1);
	}
}
Output
ArrayList Elements
[Beginner, Java, tutorial]
LinkedList Elements
[Beginner, Java, tutorial]
Set Elements
[tutorial, Beginner, Java]
Map Elements
{Tutorial=Site, Windows=98, Win=XP, Beginner=Java}


Java ArrayList

public class ArrayList<E>
extends AbstractList<E>
implements List<E>, RandomAccess, Cloneable, Serializable
  • Resizable-array implementation of the List interface. A java ArrayList is used to store an “ordered” group of elements where duplicates are allowed.
  • Implements all optional list operations, and permits all elements, including null.
  • This class is similar to Vector, except that it is unsynchronized.
  • The size, isEmpty, get, set, iterator, and listIterator operations run in constant time. ArrayList’s give great performance on get() and set() methods, but do not perform well on add() and remove() methods when compared to a LinkedList.
  • An ArrayList capacity is the size of the array used to store the elements in the list. As elements are added to anArrayList, its capacity grows automatically. It is an Array based implementation where elements of the List can be accessed directly through get() method.
To prevent unsynchronized access to the list: List list = Collections.synchronizedList(new ArrayList(…));
Below is an ArrayList Example showing how collections are manipulated using an ArrayList
import java.util.List;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.ListIterator;
import java.util.Collections;
import java.util.Random;

public class ArrayListExample {

	public static void main(String[] args) {
		//        ArrayList Creation
		List arraylistA = new ArrayList();
		List arraylistB = new ArrayList();
		//        Adding elements to the ArrayList
		for (int i = 0; i < 5; i++) {
			arraylistA.add(new Integer(i));
		}
		arraylistB.add("beginner");
		arraylistB.add("java");
		arraylistB.add("tutorial");
		arraylistB.add(".");
		arraylistB.add("com");
		arraylistB.add("java");
		arraylistB.add("site");
		//      Iterating through the ArrayList to display the Contents.
		Iterator i1 = arraylistA.iterator();
		System.out.print("ArrayList arraylistA --> ");
		while (i1.hasNext()) {
			System.out.print(i1.next() + " , ");
		}
		System.out.println();
		System.out.print("ArrayList arraylistA --> ");
		for (int j = 0; j < arraylistA.size(); j++) {
			System.out.print(arraylistA.get(j) + " , ");
		}
		System.out.println();
		Iterator i2 = arraylistB.iterator();
		System.out.println("ArrayList arraylistB --> ");
		while (i2.hasNext()) {
			System.out.print(i2.next() + " , ");
		}
		System.out.println();
		System.out.println();
		System.out
				.println("Using ListIterator to retrieve ArrayList Elements");
		System.out.println();
		ListIterator li1 = arraylistA.listIterator();
		//       next(), hasPrevious(), hasNext(), hasNext() nextIndex() can be used with a
		//        ListIterator interface implementation
		System.out.println("ArrayList arraylistA --> ");
		while (li1.hasNext()) {
			System.out.print(li1.next() + " , ");
		}
		System.out.println();
		//        Searching for an element in the ArrayList
		int index = arraylistB.indexOf("java");
		System.out.println("'java' was found at : " + index);
		int lastIndex = arraylistB.lastIndexOf("java");
		System.out.println("'java' was found at : " + lastIndex
				+ " from the last");
		System.out.println();
		//        Getting the subList from the original List
		List subList = arraylistA.subList(3, arraylistA.size());
		System.out.println("New Sub-List(arraylistA) from index 3 to "
				+ arraylistA.size() + ": " + subList);
		System.out.println();
		//        Sort an ArrayList
		System.out.print("Sorted ArrayList arraylistA --> ");
		Collections.sort(arraylistA);
		System.out.print(arraylistA);
		System.out.println();
		//      Reversing an ArrayList
		System.out.print("Reversed ArrayList arraylistA --> ");
		Collections.reverse(arraylistA);
		System.out.println(arraylistA);
		System.out.println();
		//		Checking emptyness of an ArrayList
		System.out.println("Is arraylistA empty?   "
				+ arraylistA.isEmpty());
		System.out.println();
		//        Checking for Equality of ArrayLists
		ArrayList arraylistC = new ArrayList(arraylistA);
		System.out.println("arraylistA.equals(arraylistC)? "
				+ arraylistA.equals(arraylistC));
		System.out.println();
		//      Shuffling the elements of an ArrayList in Random Order
		Collections.shuffle(arraylistA, new Random());
		System.out
				.print("ArrayList arraylistA after shuffling its elements--> ");
		i1 = arraylistA.iterator();
		while (i1.hasNext()) {
			System.out.print(i1.next() + " , ");
		}
		System.out.println();
		System.out.println();
		//        Converting an ArrayList to an Array
		Object[] array = arraylistA.toArray();
		for (int i = 0; i < array.length; i++) {
			System.out.println("Array Element [" + i + "] = " + array[i]);
		}
		System.out.println();
		//        Clearing ArrayList Elements
		arraylistA.clear();
		System.out.println("arraylistA after clearing  : " + arraylistA);
		System.out.println();
	}
}

Output
ArrayList arraylistA –> 0 , 1 , 2 , 3 , 4 ,
ArrayList arraylistA –> 0 , 1 , 2 , 3 , 4 ,
ArrayList arraylistB –>
beginner , java , tutorial , . , com , java , site ,
Using ListIterator to retrieve ArrayList Elements
ArrayList arraylistA –>
0 , 1 , 2 , 3 , 4 ,
‘java’ was found at : 1
‘java’ was found at : 5 from the last
New Sub-List(arraylistA) from index 3 to 5: [3, 4]
Sorted ArrayList arraylistA –> [0, 1, 2, 3, 4]
Reversed ArrayList arraylistA –> [4, 3, 2, 1, 0]
Is arraylistA empty? false
arraylistA.equals(arraylistC)? true
ArrayList arraylistA after shuffling its elements–> 3 , 2 , 1 , 0 , 4 ,
Array Element [0] = 3
Array Element [1] = 2
Array Element [2] = 1
Array Element [3] = 0
Array Element [4] = 4
arraylistA after clearing : []

JavaLinked List


  • A LinkedList is used to store an “ordered” group of elements where duplicates are allowed.
  • A LinkedList is based on a double linked list where elements of the List are typically accessed throughadd() and remove() methods.
Below is an LinkedList Example showing how collections are manipulated using an LinkedList
import java.util.List;
import java.util.LinkedList;
import java.util.Iterator;
import java.util.ListIterator;
import java.util.Collections;
import java.util.Random;

public class LinkedListExample {

	public static void main(String[] args) {
		//        LinkedList Creation
		List linkedListA = new LinkedList();
		List linkedListB = new LinkedList();
		//        Adding elements to the LinkedList
		for (int i = 0; i < 5; i++) {
			linkedListA.add(new Integer(i));
		}
		linkedListB.add("beginner");
		linkedListB.add("java");
		linkedListB.add("tutorial");
		linkedListB.add(".");
		linkedListB.add("com");
		linkedListB.add("java");
		linkedListB.add("site");
		//      Iterating through the LinkedList to display the Contents.
		Iterator i1 = linkedListA.iterator();
		System.out.print("LinkedList linkedListA --> ");
		while (i1.hasNext()) {
			System.out.print(i1.next() + " , ");
		}
		System.out.println();
		System.out.print("LinkedList linkedListA --> ");

		for (int j = 0; j < linkedListA.size(); j++) {
			System.out.print(linkedListA.get(j) + " , ");
		}
		System.out.println();
		Iterator i2 = linkedListB.iterator();
		System.out.println("LinkedList linkedListB --> ");
		while (i2.hasNext()) {
			System.out.print(i2.next() + " , ");
		}
		System.out.println();
		System.out.println();
		System.out
				.println("Using ListIterator to retrieve LinkedList Elements");
		System.out.println();
		ListIterator li1 = linkedListA.listIterator();
		//       next(), hasPrevious(), hasNext(), hasNext() nextIndex() can be used with a
		//        ListIterator interface implementation
		System.out.println("LinkedList linkedListA --> ");
		while (li1.hasNext()) {
			System.out.print(li1.next() + " , ");
		}
		System.out.println();
		//        Searching for an element in the LinkedList
		int index = linkedListB.indexOf("java");
		System.out.println("'java' was found at : " + index);
		int lastIndex = linkedListB.lastIndexOf("java");
		System.out.println("'java' was found at : " + lastIndex
				+ " from the last");
		System.out.println();
		//        Getting the subList from the original List
		List subList = linkedListA.subList(3, linkedListA.size());
		System.out.println("New Sub-List(linkedListA) from index 3 to "
				+ linkedListA.size() + ": " + subList);
		System.out.println();
		//        Sort an LinkedList
		System.out.print("Sorted LinkedList linkedListA --> ");
		Collections.sort(linkedListA);
		System.out.print(linkedListA);
		System.out.println();
		//      Reversing an LinkedList
		System.out.print("Reversed LinkedList linkedListA --> ");
		Collections.reverse(linkedListA);
		System.out.println(linkedListA);
		System.out.println();
		//		Checking emptyness of an LinkedList
		System.out.println("Is linkedListA empty?   "
				+ linkedListA.isEmpty());
		System.out.println();
		//        Checking for Equality of LinkedLists
		LinkedList LinkedListC = new LinkedList(linkedListA);
		System.out.println("linkedListA.equals(LinkedListC)? "
				+ linkedListA.equals(LinkedListC));
		System.out.println();
		//      Shuffling the elements of an LinkedList in Random Order
		Collections.shuffle(linkedListA, new Random());
		System.out
				.print("LinkedList linkedListA after shuffling its elements--> ");
		i1 = linkedListA.iterator();
		while (i1.hasNext()) {
			System.out.print(i1.next() + " , ");
		}
		System.out.println();
		System.out.println();
		//        Converting an LinkedList to an Array
		Object[] array = linkedListA.toArray();
		for (int i = 0; i < array.length; i++) {
			System.out.println("Array Element [" + i + "] = " + array[i]);
		}
		System.out.println();
		//        Clearing LinkedList Elements
		linkedListA.clear();
		System.out.println("linkedListA after clearing  : " + linkedListA);
		System.out.println();
	}
}
Output
LinkedList linkedListA –> 0 , 1 , 2 , 3 , 4 ,
LinkedList linkedListA –> 0 , 1 , 2 , 3 , 4 ,
LinkedList linkedListB –>
beginner , java , tutorial , . , com , java , site ,
Using ListIterator to retrieve LinkedList Elements
LinkedList linkedListA –>
0 , 1 , 2 , 3 , 4 ,
‘java’ was found at : 1
‘java’ was found at : 5 from the last
New Sub-List(linkedListA) from index 3 to 5: [3, 4]
Sorted LinkedList linkedListA –> [0, 1, 2, 3, 4]
Reversed LinkedList linkedListA –> [4, 3, 2, 1, 0]
Is linkedListA empty? false
linkedListA.equals(LinkedListC)? true
LinkedList linkedListA after shuffling its elements–> 3 , 2 , 4 , 0 , 1 ,
Array Element [0] = 3
Array Element [1] = 2
Array Element [2] = 4
Array Element [3] = 0
Array Element [4] = 1
linkedListA after clearing : []

Java TreeSet


public class TreeSet<E>
extends AbstractSet<E>
implements SortedSet<E>, Cloneable, Serializable
  • This class implements the Set interface and guarantees that the sorted set will be in ascending element order, sorted according to the natural order of the elements or by the comparator provided at set creation time, depending on which constructor is used.
  • This implementation not synchronized provides guaranteed log(n) time cost for the basic operations (add, remove and contains).
To prevent unsynchronized access to the Set.: SortedSet s = Collections.synchronizedSortedSet(new TreeSet(..));
Below is a TreeSet Example showing how collections are manipulated using a TreeSet
import java.util.Set;
import java.util.TreeSet;
import java.util.Iterator;

public class TreeSetExample {

	public static void doTreeSetExample() {
	}
	public static void main(String[] args) {
		Set treeSet = new TreeSet();
		// the treeset stores Integer objects into the TreeSet
		for (int i = 0; i < 5; i++) {
			treeSet.add(new Integer(i));
		}
		// Since its a Integer Object Set adding any other elements in the Same
		// set will produce a
		// ClassCastException exception at runtime.
		// treeSet.add("a string");
		System.out.print("The elements of the TreeSet are : ");

		Iterator i = treeSet.iterator();
		while (i.hasNext()) {
			System.out.print(i.next() + "\t");
		}
	}
}
Output
The elements of the TreeSet are : 0 1 2 3 4

Java HashMap


  • The java HashMap class does not guarantee that the order will remain constant over time.
  • This implementation provides constant-time performance for the basic operations (get and put), assuming the hash function disperses the elements properly among the buckets.
  • The HashMap implementation is not synchronized. If multiple threads access this map concurrently, and at least one of the threads modifies the map structurally, it must be synchronized externally.
To prevent unsynchronized access to the Map: Map m = Collections.synchronizedMap(new HashMap(…));
Below is a HashMap Example used to store the number of words that begin with a given letter
/*
 *  Using a HashMap to store the number of words that begin with a given letter.
 */
import java.util.HashMap;

public class HashMapExample {

	static String[] names = { "heman", "bob", "hhh", "shawn", "scot","shan", "keeth" };
	private static HashMap counter = new HashMap();
	private static Integer cnt = null;
	public static void main(String args[]) {
		for (int i = 0; i < names.length; i++) {
			cnt = (Integer) (counter.get(new Character(names[i].charAt(0))));
			if (cnt == null) {
				counter.put(new Character(names[i].charAt(0)),new Integer("1"));
			} else {
				counter.put(new Character(names[i].charAt(0)),

						new Integer(cnt.intValue() + 1));
			}
		}
		System.out.println("\nnumber of words beginning with each letter is shown below ");
		System.out.println(counter.toString());
	}
}
Output
number of words beginning with each letter is shown below
{s=3, b=1, k=1, h=2}

Java Vector


public class Vector<E>
extends AbstractList<E>
implements List<E>, RandomAccess, Cloneable, Serializable
  • The Vector class implements a growable array of objects where the size of the vector can grow or shrink as needed dynamically.
  • Like an array, it contains components that can be accessed using an integer index.
  • An application can increase the capacity of a vector before inserting a large number of components; this reduces the amount of incremental reallocation.
Below is a Vector Example showing how collections are manipulated using a Vector
import java.awt.Container;
import java.awt.FlowLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
import java.util.Enumeration;
import java.util.NoSuchElementException;
import java.util.Vector;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JTextField;

public class VectorDemo extends JFrame {

	private JLabel jlbString = new JLabel("Enter a string");
	public VectorDemo() {
		super("Vector class demo");
		// Made final as it can be accessed by inner classes
		final JLabel jlbStatus = new JLabel();
Container contentPane = getContentPane(); final Vector vector = new Vector(1); contentPane.setLayout(new FlowLayout()); contentPane.add(jlbString); final JTextField jtfInput = new JTextField(10); contentPane.add(jtfInput); JButton jbnAdd = new JButton("Add"); jbnAdd.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { vector.addElement(jtfInput.getText().trim()); jlbStatus.setText("Appended to end: " + jtfInput.getText().trim()); jtfInput.setText(""); } }); contentPane.add(jbnAdd); JButton jbnRemove = new JButton("Remove"); jbnRemove.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { // Returns true if element in vector if (vector.removeElement(jtfInput.getText().trim())) jlbStatus.setText("Removed: " + jtfInput.getText()); else jlbStatus.setText(jtfInput.getText().trim() + " not in vector"); } }); contentPane.add(jbnRemove); JButton jbnFirst = new JButton("First"); jbnFirst.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { try { jlbStatus.setText("First element: " + vector.firstElement()); } catch (NoSuchElementException exception) { jlbStatus.setText(exception.toString()); } } }); contentPane.add(jbnFirst); JButton jbnLast = new JButton("Last"); jbnLast.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { try { jlbStatus.setText("Last element: " + vector.lastElement()); } catch (NoSuchElementException exception) { jlbStatus.setText(exception.toString()); } } }); contentPane.add(jbnLast); JButton jbnEmpty = new JButton("Is Empty?"); jbnEmpty.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { jlbStatus.setText(vector.isEmpty() ? "Vector is empty" : "Vector is not empty"); } }); contentPane.add(jbnEmpty); JButton jbnContains = new JButton("Contains"); jbnContains.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { String searchKey = jtfInput.getText().trim(); if (vector.contains(searchKey)) { jlbStatus.setText("Vector contains " + searchKey); } else { jlbStatus.setText("Vector does not contain " + searchKey); } } }); contentPane.add(jbnContains); JButton jbnFindElement = new JButton("Find"); jbnFindElement.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { jlbStatus.setText("Element found at location " + vector.indexOf(jtfInput.getText().trim())); } }); contentPane.add(jbnFindElement); JButton jbnTrim = new JButton("Trim"); jbnTrim.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { vector.trimToSize(); jlbStatus.setText("Vector trimmed to size"); } }); contentPane.add(jbnTrim); JButton jbnSize = new JButton("Size/Capacity"); jbnSize.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { jlbStatus.setText("Size = " + vector.size() + "; Capacity = " + vector.capacity()); } }); contentPane.add(jbnSize); JButton jbnDisplay = new JButton("Display"); jbnDisplay.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { Enumeration enum1 = vector.elements(); StringBuffer buf = new StringBuffer(); while (enum1.hasMoreElements()) buf.append(enum1.nextElement()).append(" "); JOptionPane.showMessageDialog(null, buf.toString(), "Contents of Vector", JOptionPane.PLAIN_MESSAGE); } }); contentPane.add(jbnDisplay); contentPane.add(jlbStatus); setSize(300, 200); setVisible(true); } public static void main(String args[]) { VectorDemo vectorDemo = new VectorDemo(); vectorDemo.addWindowListener(new WindowAdapter() { public void windowClosing(WindowEvent e) { System.exit(0); } }); } }
Output


Java HashTable


  • HashTable is synchronized.
  • Iterator in the HashMap is fail-safe while the enumerator for the Hashtable isn’t.
  • Hashtable doesn’t allow nulls
Below is a HashTable Example showing how collections are manipulated using a HashTable
Please Note that It must be Compiled in Java 1.4.
// Demonstrates the Hashtable class of the java.util package.

public class HashTableDemo extends JFrame {

	public HashTableDemo() {
		super(" Hashtable Sourcecode Example");
		final JLabel jlbStatus = new JLabel();
		final Hashtable hashTable = new Hashtable();
		final JTextArea display = new JTextArea(4, 20);
		display.setEditable(false);
		JPanel jplNorth = new JPanel();
		jplNorth.setLayout(new BorderLayout());
		JPanel jplNorthSub = new JPanel();
		jplNorthSub.add(new JLabel("Name (Key)"));
		final JTextField jtfFirstName = new JTextField(8);
		jplNorthSub.add(jtfFirstName);
		jplNorthSub.add(new JLabel("Phone No"));
		final JTextField jtfPhone = new JTextField(8);
		jplNorthSub.add(jtfPhone);
		jplNorth.add(jplNorthSub, BorderLayout.NORTH);
		jplNorth.add(jlbStatus, BorderLayout.SOUTH);
		JPanel jplSouth = new JPanel();
		jplSouth.setLayout(new GridLayout(2, 5));
		JButton jbnAdd = new JButton("Add");
jbnAdd.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { String strNum = jtfPhone.getText().trim(); String strName = jtfFirstName.getText().trim(); if ((strNum != null && strNum.equals("")) || (strName != null && strName.equals(""))) { JOptionPane.showMessageDialog(HashTableDemo.this, "Please enter both Name and Phone No"); return; } int num = 0; try { num = Integer.parseInt(strNum); } catch (NumberFormatException ne) { ne.printStackTrace(); } EmployeeDetails emp = new EmployeeDetails(strName, num); Object val = hashTable.put(strName, emp); if (val == null) jlbStatus.setText("Added: " + emp.toString()); else jlbStatus.setText("Added: " + emp.toString() + "; Replaced: " + val.toString()); } }); jplSouth.add(jbnAdd); JButton jbnGet = new JButton("Get"); jbnGet.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { Object val = hashTable.get(jtfFirstName.getText().trim()); if (val != null) jlbStatus.setText("Get: " + val.toString()); else jlbStatus.setText("Get: " + jtfFirstName.getText()+ " not in table"); } }); jplSouth.add(jbnGet); JButton jbnRemove = new JButton("Remove Name"); jbnRemove.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { Object val = hashTable.remove(jtfFirstName.getText() .trim()); if (val != null) jlbStatus.setText("Remove: " + val.toString()); else jlbStatus.setText("Remove: " + jtfFirstName.getText()+ " not in table"); } }); jplSouth.add(jbnRemove); JButton jbnIsEmpty = new JButton("Empty ?"); jbnIsEmpty.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { jlbStatus.setText("Empty: " + hashTable.isEmpty()); } }); jplSouth.add(jbnIsEmpty); JButton jbnContains = new JButton("Contains key"); jbnContains.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { jlbStatus.setText("Contains key: "+ hashTable.containsKey(jtfFirstName.getText().trim())); } }); jplSouth.add(jbnContains); JButton jbnClear = new JButton("Clear table"); jbnClear.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { hashTable.clear(); jlbStatus.setText("HashTable Emptied"); } }); jplSouth.add(jbnClear); JButton jbnDisplay = new JButton("List objects"); jbnDisplay.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { StringBuffer buf = new StringBuffer(); for (Enumeration enum = hashTable.elements(); enum.hasMoreElements();) buf.append(enum.nextElement()).append('\n'); display.setText(buf.toString()); } }); jplSouth.add(jbnDisplay); JButton jbnKeys = new JButton("List keys"); jbnKeys.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { StringBuffer buf = new StringBuffer(); for (Enumeration enum = hashTable.keys(); enum.hasMoreElements();) buf.append(enum.nextElement()).append('\n'); JOptionPane.showMessageDialog(null, buf.toString(), "Display Keys of HashTable ",JOptionPane.PLAIN_MESSAGE); } }); jplSouth.add(jbnKeys); Container c = getContentPane(); c.add(jplNorth, BorderLayout.NORTH); c.add(new JScrollPane(display), BorderLayout.CENTER); c.add(jplSouth, BorderLayout.SOUTH); setSize(540, 300); setVisible(true); } public static void main(String args[]) { HashTableDemo hashTableDemo = new HashTableDemo(); hashTableDemo.addWindowListener(new WindowAdapter() { public void windowClosing(WindowEvent e) { System.exit(0); } }); } } class EmployeeDetails { private String name; private int phoneNp; public EmployeeDetails(String fName, int phNo) { name = fName; phoneNp = phNo; } public String toString() { return name + " " + phoneNp; } }
Output


Java HashSet

  • The HashSet class implements the Set interface.
  • It makes no guarantee that the order of elements will remain constant over time.
  • This class is not synchronized and permits a null element.
  • This class offers constant time performance for the basic operations (add, remove, contains and size), assuming the hash function disperses the elements properly among the buckets.
  • To prevent unsynchronized access to the Set: Set s = Collections.synchronizedSet(new HashSet(…));
Below is a HashSet Example showing how collections are manipulated using a HashSet
import java.util.*;

public class HashSetExample {

	private static String names[] = { "bob", "hemanth", "hhh", "hero",
			"shawn", "bob", "mike", "Rick", "rock", "hemanth", "mike",
			"undertaker" };
	public static void main(String args[]) {
		ArrayList aList;
		aList = new ArrayList(Arrays.asList(names));
		System.out.println("The names elements " + aList);
		HashSet ref = new HashSet(aList); // create a HashSet
		Iterator i = ref.iterator();
		System.out.println();
		System.out.print("Unique names are: ");
		while (i.hasNext())
			System.out.print(i.next() + " ");
		System.out.println();
	}
}
Output
The names elements [bob, hemanth, hhh, hero, shawn, bob, mike, Rick, rock, hemanth, mike, undertaker]
Unique names are: hhh hero bob Rick shawn hemanth rock mike undertaker