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

Discussion

What will be the output of the program?

import java.util.*;

public class Demo96
{
    static class Box
    {
        int v;
        Box(int v) { this.v = v; }

        public boolean equals(Object o)
        {
            return o instanceof Box && ((Box) o).v == v;
        }

        public int hashCode() { return 1; }
    }

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

  • A.The program prints 2 false
  • B.The program prints 1 false
  • C.The program prints 1 true
  • D.The program prints 2 true

Answer: D

A constant hashCode is legal: the contract only requires equal objects to share a hash, not unequal ones to differ. Both boxes land in the same bucket, where equals separates them, so the size is 2 and the lookup succeeds. The cost is performance, since the bucket degenerates into a linear scan.

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

Post your comment

Please log in or register to post a comment.