Print the number of unique pairs Stored in a HashSet
Clearly, janos solution is the simplest, but it'd probably break for the input

a b
a  b


Moreover, it circumvents the learning effect (I guess, it's about learning to write a class with equals and hashCode).

As often, Lombok makes it trivial:

@EqualsAndHashCode
public static class Pair {
    private final String first, second;
}


hashCode

The inefficiency was most probably caused by

@Override public int hashCode() {
    return first.hashCode();
}


which is correct, but leads to many collisions due to ignoring second. Something like

    return first.hashCode() + 123456789 * second.hashCode();


would solve it (the multiplier should be odd, anything else doesn't matter much).

equals

  return (first.equals(otherPair.first) &amp;&amp; second.equals(otherPair.second))
            || (first.equals(otherPair.second) &amp;&amp; second.equals(otherPair.first));


This contradicts the part


  implies (a,b) is not same as (b,a).


If it ever worked, then only because of the asymmetry in hashCode.

Why?

Two equals objects must have the same hashCode, otherwise the HashSet doesn't work properly (as the hash determines the index where the lookup starts). Violating this rule is a serious bug with which you may spend many funny debugging days.

This time, it helped you. After

set.put(new Pair("a", "b"));


the query

set.contains(new Pair("b", "a"));


erroneously returns false, although according to equals, the pair is there. However, it doesn't get found due to the non-equal hashCode. Analogously, after

set.put(new Pair("b", "a"));


you managed to contradict


  set is an abstract data type that can store certain values, without any particular order, and no repeated values.


Note that this is not guaranteed to happen as the hashes may coincide and only a part of them gets used.