Junior
Does HashSet allow storing objects of different data types?
sobes.tech AI
Answer from AI
Yes, it allows.
HashSet stores references to objects of type Object, which allows it to contain elements of various data types. However, due to type erasure in generics, when creating a HashSet without specifying a particular type, the compiler will treat it as HashSet<Object>.
Example:
import java.util.HashSet;
// Example of using HashSet with different data types
HashSet rawSet = new HashSet();
rawSet.add("String");
rawSet.add(123); // Autoboxing int to Integer
rawSet.add(3.14); // Autoboxing double to Double
rawSet.add(true); // Autoboxing boolean to Boolean
System.out.println(rawSet);
However, this approach is not recommended because it reduces type safety and can lead to runtime errors (e.g., ClassCastException) when retrieving elements from the collection.
When using HashSet with generics, it will only store objects of the specified type:
import java.util.HashSet;
// HashSet with specified type
HashSet<String> stringSet = new HashSet<>();
stringSet.add("First string");
stringSet.add("Second string");
// stringSet.add(123); // Compilation error: cannot add Integer to HashSet<String>
System.out.println(stringSet);
In general, to ensure type safety, always use generics when working with collections.