Problem : Create a dynamic Set that contains only unique elements.
Program :Step 1 - CodingCreate a text file c:\sunilos\TestHashSet.java and copy below contents.import java.util.*; /* * A program to implement HashSet. */ public class TestHashSet { public static void main(String[] args) { HashSet hSet = new HashSet(); // You can insert any object in the HashSet. Here it is string hSet.add("Jay"); hSet.add("Viru"); hSet.add("Basanti"); System.out.println("Some Importent Methods"); System.out.println(" Set size : " + hSet.size()); System.out.println(" Contains Jay : " + hSet.contains("Jay")); /* * Primitive data type need to be converted into Objects before * inserting. Get all elements and print with help of Iterator interface */ Iterator it = hSet.iterator(); // Get an iterator System.out.println("\nPrint All Elements with help of Iterator "); while (it.hasNext()) { // Checks if any element in list Object oo = it.next(); // Get next available element System.out.println(" From Iterator -- " + oo); } // Clear all elements hSet.clear(); System.out.println(" Is Empty " + hSet.isEmpty()); } } Step 2 - Deployment
Step 3 - Testing
OutputC:\sunilos>java TestHashSetSome Importent Methods Set size : 3 Contains Jay : true Print All Elements with help of Iterator From Iterator -- Jay From Iterator -- Viru From Iterator -- Basanti Is Empty true FAQWhat is HashSet ?This class implements the Set interface, backed by a hash table (actually a HashMap instance).This class permits the null element. When you gets elements through Iterator, elements order may be changed. Is HashSet thread-safe?No it is not synchronized, if you want to make it thread safe then synchronize it with help of below commandSet s = Collections.synchronizedSet(new HashSet()); Most Interesting methods in HashSet?
<<Previous | Next>> |