-1

I have this uml diagram and I don't understand a part of a code that I have from my friend . I don't understand the "equals" method.. What is used for and why should I use it ?
This is the UML : enter image description here

But I don't understand some part of the code .

this is a part of the code so far :

class Artist { 

private String name;

Artist(String name) { // constructor
    this.name = name;
}

public String getName() { // name getter
    return name;
}

public String toString() { // toString
    return name;
}
}

class CD { 
private String title;
private Artist name;

CD(String title) {
    this.title = title;
}

CD(String title, Artist name) {
    this.title = title;
    this.name = name;
}

public Artist getArtist() {
    return name;
}

public String getTitle() {
    return title;
}

public String toString() {
    return title + " by " + getArtist();
}

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

}

Basket777
  • 17
  • 1
  • 8
  • 2
    Read the [answers in this post](https://stackoverflow.com/questions/15175109/why-do-we-have-to-override-the-equals-method-in-java). – Juan Carlos Mendoza Aug 18 '17 at 13:03
  • 1
    Possible duplicate of [Why do we have to override the equals() method in Java?](https://stackoverflow.com/questions/15175109/why-do-we-have-to-override-the-equals-method-in-java) – qwerty_so Aug 18 '17 at 13:12

2 Answers2

1

The class diagram misses that CD inherits from a general Object which provides an equals method. Correctly it should look like

enter image description here

(My Java knowledge is near to null.)

qwerty_so
  • 35,448
  • 8
  • 62
  • 86
1

Equals method is a wrapper class to perform numerical comparison.In layman terms it like comparing two number. example x = 10, y =20 is x=y? answer is no. The same in java you have equals method which returns true if the x=y else returns false. In your case in the code he is overriding the method equals, to customise the comparison in the code. He is comparing the two CD objects if they are equal it return true else it returns false.