Java Collections: HashSet Example

  • 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]

 

No comments:

Post a Comment

12 classic String-based Java interview questions with simple explanations and code.

  1️⃣ Check if a String is a Palindrome Problem Given a string, check if it reads the same forward and backward. Example: "madam...

Featured Posts