Monday, January 16, 2012

HashSet

import java.util.*;
class HashSetDemo
{
public static void main(String args[])
{
//create HashSet
HashSet<String> hs=new HashSet<String>();
hs.add("B");
hs.add("A");
hs.add("D");
hs.add("E");
hs.add("C");
hs.add("F");
System.out.println(hs);

//Iterator to display elements
System.out.print("Displaying contents of hs using Iterator: ");
Iterator itr=hs.iterator();
while(itr.hasNext())
{
Object element=itr.next();
System.out.print(element + " ");
}
System.out.println();

//For each, alternative to iterator
System.out.print("Displaying contents of hs using for each: ");
for(String s:hs)
System.out.print(s + " ");
System.out.println();
//--------------------------------------------------------
//adding a to z in HashSet
System.out.println();
HashSet<Character> h=new HashSet<Character>();
for(int i=97;i<122;i++)
h.add((char)i);
h.add('b');
System.out.println(h);

//Iterator to display elements
System.out.println("Displaying contents of h using Iterator: ");
Iterator itr1=h.iterator();
while(itr1.hasNext())
{
Object element=itr1.next();
System.out.print(element + "-");
}
System.out.println();

//For each, alternative to iterator
System.out.println("Displaying contents of h using for each: ");
for(Character s1:h)
System.out.print(s1 + " ");
System.out.println();

}
}

Output:
[D, E, F, A, B, C]
Displaying contents of hs using Iterator: D E F A B C
Displaying contents of hs using for each: D E F A B C

[f, g, d, e, b, c, a, n, o, l, m, j, k, h, i, w, v, u, t, s, r, q, p, y, x]
Displaying contents of h using Iterator:
f-g-d-e-b-c-a-n-o-l-m-j-k-h-i-w-v-u-t-s-r-q-p-y-x-
Displaying contents of h using for each:
f g d e b c a n o l m j k h i w v u t s r q p y x

Note:
  • HashSet does not guarantee the order of its elements
  • In HashSet ListIterator cannot be used.
  • HashSet implements Set Interface.



No comments:

Post a Comment