JavaLearner
JavaLearner

Reputation: 17

Why does the HashMap value returns null and string values when executed several times?

Here is my code:

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;
    }

}

And the driver class:

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);

    }
}

The value s returns both null values and the string values(" 2 två two") when executed several times?

Upvotes: 0

Views: 216

Answers (1)

Daniel Fischer
Daniel Fischer

Reputation: 183878

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

shouldn't that have been x2? Whenever you look for a new X(2), you get null.

Upvotes: 6

Related Questions