Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

overriding equal and hashcode in Java where this.obj is null

Hi I am trying to overriding the equal and hashcode method in for my custom class .

here is my custom class

public class property
{
    public String type = null;
    public int value;
    public int id;
    public String name = null;
    public String course = null;



    public property(String type, String course, int value, int id)
    {
        this.value = value;
        this.type = type;
        this.course = course;
        this.id = id;
    }

    @Override
    public boolean equals(Object obj) {
        if(this == obj)
            return true;
        if((obj == null) || (obj.getClass() != this.getClass()))
            return false;

        property sig = (property) obj;

        if(sig != null) {
            if(sig.type.equals("EST1")) {
                if (sig.name != null && sig.type != null && sig.course != null) {
                    Log.d("property", "Other   " + sig.course + "AHHAHAHA " + course + "shahahaaha " + sig.id + "babababaab " + id);
                    if (sig.course.equals(this.course) && sig.value == this.value && sig.type.equals(this.type) && sig.id == (this.id)) {
                        Log.d("property", "EST1");
                        return true;
                    }

            }

        }
        return false;
}

The problem is that "this.id, this.type" is always null or 0 I do not understand why...while sig.id, sig.type have values. Just to let you know it is only code snippet, not full code so it might have typos and not logically correct..

like image 415
user3290805 Avatar asked Aug 03 '26 12:08

user3290805


1 Answers

Your code works well in my side, so I guess your test program is somewhat different (or complicated?) from mine.

I tried following for test,

property p = new property("a","b", 100, 200);
System.out.println("id:"+p.id);
System.out.println("type:"+p.type);
System.out.println(p.equals(p) +" should be true..");

And I got,

id:200
type:a
true should be true..
like image 153
fcmonoid Avatar answered Aug 06 '26 01:08

fcmonoid