1

I'm currently studying a course in data structures & algorithms, and we have got an assignment from our teacher to create a hashtable with chaining as a collision resolution technique.

For each entry in the hash table our teacher wants us to have this equals method:

 @Override
 public boolean equals(Object obj) {
     Entry keyToCompare = new Entry(obj, null);
     return key.equals(keyToCompare.key);
 }

What is the difference when writing it like this compared to if I just compare the keys with the regular .equals?

Here is the complete class:

public class Entry<T> {

    private Object key;
    private Object value;

    public Entry(T key, T value){
        this.key = key;
        this.value = value;
    }

    public boolean equals(Object obj){
        //What i think should work
        return key.equals(obj);
    }
}
home
  • 12,468
  • 5
  • 46
  • 54
  • 1
    The only difference is that you create an unnecessary object in the first case. It's like putting a mug away in a cupboard, then getting it out again to make a cup of tea - you still get your tea, you just put in unnecessary effort. – Andy Turner Sep 22 '16 at 16:15
  • I removed the tag "adt" as this does not seem to relate to android development. – home Sep 22 '16 at 16:15
  • 1
    One problem would be that `Entry.equals()` would not be symmetric, i.e. `obj.equals(entry)` would probably return a different result than `entry.equals(obj)` - and this might break the table, e.g. if it at some point calls the former and relys on the contract on `equals()` (see JavaDoc) which requires it to be symmetric. - That being said the `equals()` you mentioned first (the one you are meant to use) suffers from the same problem. Normally I'd create the `Entry` instance outside the method and pass it to `equals()`, i.e. `entry.equals(new Entry(obj, null));`. – Thomas Sep 22 '16 at 16:17
  • You might want to talk to [Marante](http://stackoverflow.com/q/39637661/3788176), who appears to be working on exactly the same problem. (I made a comment on his/her question, asking about exactly the same point you raise here). – Andy Turner Sep 22 '16 at 16:17
  • Oh. i saw ADT as Abstract Data Types haha. My bad – Christoffer Strandberg Sep 22 '16 at 16:23
  • @Thomas So I might as well use the second one? I have to talk to my teacher about this. The last assignment we got was on Stacks and there were some unnecessary code there as well that she wanted us to write. But I did it my way and everything worked perfectly – Christoffer Strandberg Sep 22 '16 at 16:26
  • You should use neither because `equals` must comply with its contract. Your equals breaks _all_ of the specified properties of reflexivity, symmetry, and transitivity. – Marko Topolnik Sep 22 '16 at 17:39

0 Answers0