Junior — Middle
Can elements of different data types be added to a HashSet collection?
sobes.tech AI
Answer from AI
In Java, a collection of type HashSet is parameterized with a generic, for example, HashSet<String> or HashSet<Object>. If you declare HashSet<Object>, technically, you can add objects of any type, since all classes in Java inherit from Object.
However, if the collection is parameterized with a specific type, such as HashSet<String>, then adding elements of other types is not allowed — the compiler will produce an error.
Example:
HashSet<Object> set = new HashSet<>();
set.add("string");
set.add(123); // allowed
HashSet<String> stringSet = new HashSet<>();
stringSet.add("text");
// stringSet.add(123); // compile-time error
Thus, you can add elements of different types if the collection is declared with the Object type or without parameterization (which is not recommended). But usually, specific types are used for type safety.