Valter Silva
Valter Silva

Reputation: 16656

Comparison should return true but return false

I have two objects with the same type, then I'm trying to see if they're are equal, but it seems they're not, and I really don't understand why this is happening, I took a picture from the screen where you guys can see what I'm trying to say:

here (with high resolution).

The image is to show you guys what is really happening even debbuging.

Here's the code and the classes :

private boolean checkForExpr(Type lowerExprType, Type upperExprType) {
    boolean result = false;
    if (lowerExprType == Type.undefinedType || upperExprType == Type.undefinedType){
        return false;
    }else{
        result = (lowerExprType == upperExprType);
    }
        return result;
}

Type class

abstract public class Type {

    public Type( String name ) {
        this.name = name;
    }

    public static Type booleanType = new BooleanType();
    public static Type integerType = new IntegerType();
    public static Type charType    = new CharType();
    public static Type undefinedType = new UndefinedType();

    public String getName() {
        return name;
    }

    abstract public String getCname();

    private String name;
}

IntegerType class

public class IntegerType extends Type {

    public IntegerType() {
        super("integer");
    }

   public String getCname() {
      return "int";
   }

}

Upvotes: 0

Views: 883

Answers (3)

Pramod Kumar
Pramod Kumar

Reputation: 8014

Override object class's equals and hashCode methods.

Upvotes: 0

Himanshu Mohta
Himanshu Mohta

Reputation: 1043

In line result = (lowerExprType == upperExprType) you are comparing the references not String.

Type class:

abstract public class Type {

public Type( String name ) {
    this.name = name;
}

public static Type booleanType = new BooleanType();
public static Type integerType = new IntegerType();
public static Type charType    = new CharType();
public static Type undefinedType = new UndefinedType();

@Override
public String toString() {
    return name;
}
private String name;

}

IntegerType class:

public class IntegerType extends Type {

public IntegerType() {
    super("integer");
}

}

Upvotes: 0

Andrew T Finnell
Andrew T Finnell

Reputation: 13638

You are checking to see if it is the same reference to the same object. Which according to your debugger they are not. Look at the (id=) fields in the debugger. The String "integer" has the same (id=) but your two Type objects are different.

You need to implement equals and hashCode and then check the internal object properties such as this:

abstract public class Type {
    @Override
    public boolean equals(Object obj){
        if (obj instanceof Type) {
            return name.equals (((Type)obj).getName());
        }
        return false;
    }   
}

You should probably check for nulls etc.

Check out the answer to this question Override the equals method

Upvotes: 6

Related Questions