Set - HashSet does not allow duplicates
There was a reason for the creation of the Set
interface; it was designed not to allow duplicate elements. A duplicate is identified using the equals()
method, implemented in the class whose objects are elements of the set.
Preferring variable type Set
As in the case of List
, using type Set
for the variable that holds a reference to the object of the class that implements the Set
interface is a good programming practice called coding to an interface. It assures independence of the client code from any particular implementation. So, it is a good habit to write Set<Person> persons = new HashSet<>()
, for example.
Why is it called HashSet?
In programming, a hash value is a 32-bit signed integer that represents some data. It is used in such data structures as a HashTable
. After a record is created in a HashTable
, its hash value can be used later to quickly find and retrieve the stored data. A hash value is also called a hash code, digest, or simply...