0
public V find(K key){
     for (int i = getHashValue(key); table[i] != null; i = (i + 1) % thesize)
           if (table[i].key == key)
               return table[i].value;
    //if the key not found
          System.out.println(" Could not find '" + key.toString() +"'s value");
        return null;

The find method supposed to return key's value but it doesn't. I can't understand where is the mistake. I used (==) but still not working. I would appreciate for the help.

b.alex
  • 107
  • 1
  • 1
  • 5
  • Are you sure the key is even in the table? In the right spot? How do you know? – Andreas Mar 31 '18 at 19:36
  • the key is in the table. I inserted keys and values in main method. @Andreas – b.alex Mar 31 '18 at 19:49
  • [The linked post](https://stackoverflow.com/questions/13387742/compare-two-objects-with-equals-and-operator) should tell you that you **shouldn't** use `==`. See also [Equals method for objects](https://stackoverflow.com/q/3950439), which maybe does a better job of that. – Bernhard Barker Mar 31 '18 at 20:01
  • I use if (key.equals(table[i].key)) but still not returning value @Dukeling – b.alex Mar 31 '18 at 20:31
  • Then can you post a [mcve] (assuming constructing one, including [debugging](https://ericlippert.com/2014/03/05/how-to-debug-small-programs/) doesn't lead to an answer)? – Bernhard Barker Mar 31 '18 at 20:46

1 Answers1

0

If you sure that the value of your key is existed on the table then your issue is related to == operator, in Java == return true for object, if the two operands point to the same object (not equivalent objects, the same object.

so in this case you have to convert your if to be as the following

   if (key.equals(table[i].key)) 

And make sure to override equals method on your key object,if you're using a custom object.

please read this how-to-override-equals-method-in-java for more info

Ahmad Al-Kurdi
  • 2,248
  • 3
  • 23
  • 39
  • what do you mean by override equals method? @Ahmed Al-Kurdi. – b.alex Mar 31 '18 at 20:13
  • 2
    @b.alex [How to override equals method in java](https://stackoverflow.com/q/8180430). This is only applicable if you're using a custom object (a class from the standard API, like `String`, should already have an overridden `equals` method). Although you should probably read a textbook or something if you don't know what "override equals method" means - that's some pretty fundamental knowledge. – Bernhard Barker Mar 31 '18 at 20:56
  • @Dukeling, thanks for your comments, b.ales I just updated my answer – Ahmad Al-Kurdi Apr 01 '18 at 08:07