- 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
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:
Post a Comment