0

这是我的代码:

package AbstractClassesTwo;

class X {
    private int n;

    public X(int n){
        this.n = n;
    }

    public String toString(){
        return "[" + n + " ]";
    }

    public boolean equals (Object obj){
        boolean b = false;
        if(obj instanceof X){
            X x = (X)obj;
            b = this.n == x.n;
        }

        return b;
    }

    public int hashCode(){
        return n;
    }

}

和驱动程序类:

package AbstractClassesTwo;

import java.util.HashMap;

public class UseX {

    public static void main (String[] args){

        X x1 = new X(1);
        X x2 = new X(2);

        String s1 = "1 ett one";
        String s2 = "2 två two";

        HashMap<X, String> t = new HashMap<X, String>();
        t.put(x1, s1);
        t.put(x1, s2);

        int i = (int) (2 * Math.random() + 1);
        X n = new X(i);
        String s = (String)t.get(n);

        System.out.println(n + ": " + s);

    }
}

" 2 två two"值 s在多次执行时返回 null 值和字符串 values( )?

4

1 回答 1

6
t.put(x1, s1);
t.put(x1, s2);
      ^^

不应该是这样x2吗?每当你寻找一个new X(2),你就会得到null

于 2013-01-15T23:55:41.073 回答