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

Discussion

What will be the output of the program?

import java.util.*;

public class Demo61
{
    static class Key
    {
        StringBuilder id;
        Key(String s) { id = new StringBuilder(s); }

        public boolean equals(Object o)
        {
            return o instanceof Key && (
                (Key) o).id.toString().equals(id.toString());
        }

        public int hashCode() { return id.toString().hashCode(); }
    }

    public static void main(String[] args)
    {
        Set<Key> set = new HashSet<Key>();
        Key k = new Key("a");
        set.add(k);
        k.id.append("b");
        System.out.println(set.contains(k) + " " + set.size());
    }
}

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

Answer: A

The key was filed under the hash of a, and mutating it afterwards changes the hash to that of ab, so the lookup searches the wrong bucket and reports false. The element is still in the set, so the size is 1: it has become unreachable rather than removed. Anything used as a hash key must be effectively immutable.

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

Post your comment

Please log in or register to post a comment.