Kishlin
Kishlin

Reputation: 373

Comparing objects within a set

Right now I have this Java code

import java.util.HashSet;
import java.util.Objects;
import java.util.Set;

public class Dummy {

    private String value;

    public Dummy(final String value) {
        this.value = value;
    }

    public boolean equals(final Object that) {
        return that instanceof Dummy && Objects.equals(value, ((Dummy) that).value);
    }

    public int hashcode() {
        return Objects.hash(value);
    }

    public static void main(final String... args) {
        final Set<Dummy> dummies = new HashSet<>();
        dummies.add(new Dummy("toto"));
        System.out.println(dummies.contains(new Dummy("toto")));
    }
}

The output is "false", and I'm supposed to change it to "true" by changing only one character, but I have absolutely no idea how to do that... Any ideas? Thanks. :)

Upvotes: 0

Views: 5171

Answers (3)

Marcel Zebrowski
Marcel Zebrowski

Reputation: 311

In my case I had lots of objects who all need a equals and hash method. I have used lombok to reduce the work and code.

@Data
@AllArgsConstructor
@EqualsAndHashCode
public class JsonPictureStuff {
    private String type;
    private String url;
    private String width;
    private String height;
}

The annotations instruct lombok to add the code for you.

Upvotes: 1

your set is not working because you are implementing equals and hashcode in a not proper way...

  1. specially because you are not even considering the string field
  2. you are avoiding the annotation Override that will hint you about wrongly named methods like hashcode and hashCode

you can do something like

   @Override
    public int hashCode() {
    final int prime = 31;
    int result = 1;
    result = prime * result + ((value == null) ? 0 : value.hashCode());
    return result;
    }

    @Override
    public boolean equals(Object obj) {
    if (this == obj)
        return true;
    if (obj == null)
        return false;
    if (getClass() != obj.getClass())
        return false;
    Dummy  other = (Dummy ) obj;
    if (value == null) {
        if (other.value != null)
        return false;
    } else if (!value.equals(other.value))
        return false;
    return true;
    }

in ide like eclipse you can do right click and auto generate those methods so you can save the implementation

Upvotes: 0

davidxxx
davidxxx

Reputation: 131546

hashcode() is not a Object's method but hashCode() is.

 public int hashcode() {
         return Objects.hash(value);
   }

should be

public int hashCode() {
        return Objects.hash(value);
    }

Upvotes: 7

Related Questions