Searching...
Saturday, 6 October 2012

Java Collections: HashSet Example

06:07
  • HashSet is a good choice for representing sets if order of the elements is not important
  • HashSet methods are not synchronized
  • HashSet not allowing duplicate elements

image
 

Example

package mycollectiontest;

import java.util.HashSet;
import java.util.Iterator;
import java.util.Set;

public class CollectionExample {

public static void main(String[] args) {
Set<String> set = new HashSet<String>();
set.add("Bangalore");
set.add("Chennai");
set.add("Mumbai");
set.add("Hydrabad");
// Printing set
System.out.println(set);
// Iterating and set
Iterator<String> it = set.iterator();
while (it.hasNext()) {
System.out.println("Elements " + it.next());
}

// Trying to add duplicate;
set.add("Bangalore");
System.out.println(set);
}

}

Output

[Chennai, Hydrabad, Mumbai, Bangalore]
Elements Chennai
Elements Hydrabad
Elements Mumbai
Elements Bangalore
[Chennai, Hydrabad, Mumbai, Bangalore]

 

0 comments: