Write a Java program to Create a HashSet with different types of items
The program starts with the import statement import java.util.*;, which imports all classes from the java.util package, including HashSet.
- The program defines a public class called Different_TypesItems. Within the Different_TypesItems class, the main method is declared and serves as the entry point for the program. It takes an array of strings (args) as input.
- Inside the main method, a new instance of the HashSet class is created using the constructor: HashSet dif_type = new HashSet();. Since no specific type is specified within the diamond brackets (<>), it creates a raw HashSet that can store objects of any type.
- After that, different types of elements are added to the dif_type HashSet using the add() method. The elements added include an integer (8), a string ("Tutor Joes"), a double (95.58), a character ('T'), a boolean (false), and another double (45.789784).
- Finally, the program prints the contents of the dif_type HashSet using the System.out.println() statement.
Source Code
import java.util.*;
public class Different_TypesItems
{
public static void main(String[] args)
{
HashSet dif_type = new HashSet();
dif_type.add(8);
dif_type.add("Tutor Joes");
dif_type.add(95.58);
dif_type.add('T');
dif_type.add(false);
dif_type.add(45.789784);
System.out.println("Create a HashSet with different types of items..");
System.out.println(dif_type);
}
}
Output
Create a HashSet with different types of items..
[T, false, Tutor Joes, 8, 45.789784, 95.58]