I believe in practicing algorithm is crucial for understanding the language. After spending some time of agony from facing an unsolvable problem, I had no option but to negotiate with myself to look up the answer.
I was shocked to see how concise the answer was and it used a method I have never used before, the HashSet
.
According to the Oracle documentation, Class HashSet implements the Set
interface, backed by a hash table. It does not guarantee that the order will remain constant over time.
As it implements the Set Interface, duplicate values are not allowed
Also implements Serializable
and Cloneable
interfaces. HashSet not only stores unique Objects but also a unique Collection of Objects like ArrayList<E>
, LinkedList<E>
,Vector<E>
.
import java.util.HashSet;
public class Example {
public static void main(String[] args){
HashSet<String> hs = new HashSet<String>();
hs.add("Adam");
hs.add("Park");
hs.add("Adam");
System.out.println(hs);
["Adam","Park"]
Since it does not allow any duplicate value, the second Adam does not get to be in the set.
For me personally, if I have to filter out all the duplicate integers in an integer array, I was able to solve the problem using HashSet. Utilizing HashSet on any problem related to unique value would be beneficial.
There is also a class called HashMap
. They seemed to function similarly but there are some differences.
Map
Interface.put()
method rather than add()
.