0

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";
   }

}
Valter Silva
  • 16,446
  • 52
  • 137
  • 218

3 Answers3

6

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

Community
  • 1
  • 1
Andrew T Finnell
  • 13,417
  • 3
  • 33
  • 49
0

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");
}

}

Himanshu Mohta
  • 1,033
  • 9
  • 15
0

Override object class's equals and hashCode methods.

Pramod Kumar
  • 7,914
  • 5
  • 28
  • 37