2

I'm trying to write the get method for a hashmap of custom objects.

public V get(K key){
    int hashval = (int)(Math.abs(key.hashCode()) % this.capacity);
    for(Data<K, V> d : hashmap.get(hashval) ){
        System.out.println("hashval: " + hashval);
        System.out.println("d.getKey:" + d.getKey() + " class: " + d.getKey().getClass());
        System.out.println("key:" + key + " class: " + key.getClass());

        if (d.getKey() == key){
            System.out.println("d.getValue: " + d.getValue());
            return d.getValue();
        }
    }

I would expect that if d.getKey() and key print the same value and the same class type, then the if statement should come out true, and print the value which should be being returned. However, this is the result I get:

hashval: 5  
d.getKey:12345 class: class java.lang.Integer  
key:12345 class: class java.lang.Integer  

The line inside the if statement does not show up. What silly problem am I overlooking? I think it might have something to do with templates, since key is the generic type K?

Sotirios Delimanolis
  • 274,122
  • 60
  • 696
  • 724

2 Answers2

2

if (d.getKey() == key) is not correct. you need to use if (d.getKey().equals(key))

Prabhakaran Ramaswamy
  • 25,706
  • 10
  • 57
  • 64
0

try

d.getKey().intValue() == key.intValue()

you can use == only for primitive data type, For Objects you can use equals method to compare an attribute value as

   d.getKey().equals(key)
upog
  • 4,965
  • 8
  • 42
  • 81
  • What if the key isn't an Integer? – Flight Odyssey Oct 16 '13 at 03:37
  • AS per OP's question the key is of type java.lang.Integer – upog Oct 16 '13 at 03:39
  • "you can use == only for primitive data type": this is very untrue ... but you -do- have to know what you're doing. Sometimes you actually do want to test for identity and sometimes you actually do want to test for equality. – scottb Oct 16 '13 at 03:40
  • In this test case the key was an Integer but the OP is trying to make a generic HashMap which would work for any key, right? – Flight Odyssey Oct 16 '13 at 03:45