简体   繁体   中英

Java Equals Method doesnt work

I got two "lists" of objects, which i want to compare if elements are equal. If they are not equal, the loop should take the not equal object and put it into the other list. Very simple. My problem is: the equals method doesnt work as intended.

Here is the object Class with my custom equals method:

    public class Profil {

private String vorname;
private String name;
private String adLoginBenutzer;


public Profil() {
}


public String getAdLoginBenutzer() {
    return adLoginBenutzer;
}


public void setAdLoginBenutzer(String adLoginBenutzer) {
    this.adLoginBenutzer = adLoginBenutzer;
}


public String getVorname() {
    return vorname;
}


public void setVorname(String vorname) {
    this.vorname = vorname;
}


public String getName() {
    return name;
}


public void setName(String name) {
    this.name = name;
}

@Override
public String toString() {
    if (name == null || vorname == null) {
        return "<keiner>";
    }
    return vorname + ", " + name + " " + adLoginBenutzer;
}

@Override
public boolean equals(Object obj) {
    if (getClass() != obj.getClass()) {
        return false;
    }
    Profil other = (Profil)obj;

    if(!this.getVorname().equals(other.getVorname()) || !this.getName().equals(other.getName()) || !this.getAdLoginBenutzer().equals(other.getAdLoginBenutzer()))
    {
        return false;
    }



    return true;
}

}

And here is the loop: (note: I basically want to merge the list into a comboboxmodel, if the profil-object is not equal than it should add it to the first position in the comboboxmodel)

public void putProfilesIntoCbx(HashSet<Profil> profile)
{
    DefaultComboBoxModel<Profil> cbx = (DefaultComboBoxModel <Profil>)cbBearbeiter.getModel();
    for(Profil p : profile)
    {
       for(int i = 0; i< cbx.getSize(); i++)
       {
           if(!p.equals(cbx.getElementAt(i)))
           {
               cbx.insertElementAt(p, 0);
           }
       }
    }
    cbBearbeiter.setModel(cbx);
}

I debugged the code and took breakpoints at the last if of the equals method. Although there are equal objects, the last if return false for no reason even if the objects are really equal. Even if i invert the equals if-statement it does not work.

As everyone is saying, there is a relationship between the equals() method and the hashcode() method.

If you @Override the equals() method, you need to @Override the hashcode() method as well

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM