0

Why am I getting output 2 for the following code instead of 1? HashSet does not allow duplicate elements.

import java.util.*;

import java.io.*;

import java.math.*;

public class Main1

{

    static class pair 
    {
       int x;
       int y;
       public pair (int k, int p) 
       {
           x = k;
           y = p;
       }
    }
    public static void main(String[] args)throws IOException
    {
        Set<pair> hs=new HashSet<pair>();
        hs.add(new pair(1,2));
        hs.add(new pair(1,2));
        System.out.println(hs.size());
    }
}
Md Johirul Islam
  • 5,042
  • 4
  • 23
  • 56

1 Answers1

2

You must override equals and hashcode.

From the documentation of Java's Set interface:

A collection that contains no duplicate elements. More formally, sets contain no pair of elements e1 and e2 such that e1.equals(e2), and at most one null element.

Note that the following will print false:

    pair p1 = new pair(1, 2);
    pair p2 = new pair(1, 2);
    System.out.println(p1.equals(p2));

Also note that the java convention is to start class name with capital letter.

This will do the work for you:

    class Pair {

    int x;
    int y;

    public pair(int k, int p) {
        x = k;
        y = p;
    }

    @Override
    public boolean equals(Object o) {
        if (this == o) return true;
        if (o == null || getClass() != o.getClass()) return false;
        pair pair = (pair) o;
        return x == pair.x && y == pair.y;
    }

    @Override
    public int hashCode() {
        return Objects.hash(x, y);
    }
}
Oz Molaim
  • 2,016
  • 4
  • 20
  • 29