Machine-translated by Google. Questions are authored in English.
Top

Discussion

What will be the output of the program?

import java.util.*;

public class Trial09
{
    static class Point
    {
        int x;
        Point(int x) { this.x = x; }

        public boolean equals(Object o)
        {
            return o instanceof Point && ((Point) o).x == x;
        }
    }

    public static void main(String[] args)
    {
        Set<Point> s = new HashSet<Point>();
        s.add(new Point(1));
        s.add(new Point(1));
        System.out.println(s.size());
    }
}

  • A.The program prints 2
  • B.The program prints 0
  • C.Compilation fails.
  • D.The program prints 1

Answer: A

Point overrides equals but not hashCode, so two equal points almost certainly land in different buckets and the set never compares them. Both are stored and the size is 2. Overriding equals without hashCode breaks every hash-based collection in exactly this way.

No comment is present. Be the first to comment.
Loading…

Post your comment

Please log in or register to post a comment.