looking for some solutions? You are welcome.

SOLVED: Implement equals() for a Class with Cyclic Reference Java

Nkuruza:

I want a way to override the equals method for a class that has cyclic reference. Below is my class EDIT: Removed code for getters and setters

class Person implements Serializable{
    private String fullName;
    private Person friend;
    // Getters and setters

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

And in the client class I have the following:

Person p1 = new Person();
Person p2 = new Person();
Person p3 = new Person();
p1.setFullName("nkuruza");
p2.setFullName("Another");
p3.setFullName("nkuruza");
p3.setFriend(p2);
p1.setFriend(p2);
p2.setFriend(p1);

The issue is calling the equals method in this situation, eg p1.equals(p3) produces StackOverflowException.

How can I implement my equals method without having to run into this issue?

I thank you in advance.



Posted in S.E.F
via StackOverflow & StackExchange Atomic Web Robots
Share:

No comments:

Recent