简体   繁体   中英

Using the boolean object equals() in my implemented equals()

So I am doing a junit test in Java.

I am supposed to test two concrete types

public class BoolValue implements Value{
   private boolean item; 

   //the Constructor 
   public BoolValue(boolean data){
        item = data;
   }

   //checks to see if the current object is of the same type as the parameter  
   public boolean equals(Value v){
       boolean result = false;
          if (v instanceof BoolValue) {
              if(this == v)
                  result = true; 
          }
       return result; //true if equal 
   }

    // returns current state string 
    public String toString(){
         return " "+item;

    }
 }

This is the test case in my test file

@Test
 public void testBoolean(){
     BoolValue value = new BoolValue(true); 
     BoolValue value2 = new BoolValue(true); 
     assertEquals(true, value.equals(value2));
 }

It returns false instead of the expected true

In the equals method, I want to compare two boolean types but I can't use the java.object equals() because the program reads it as the class equals() so its recursive. How do I call the java.object equals() for comparing boolean types. Also, am I going about this the right way

 if (v instanceof BoolValue) {
       if(this == v)
           result = true; 
 }

You cannot use == when you want new BoolValue(true).equals(new BoolValue(true)) . You need to compare the two item inside them.

Also, you need to accept Object to get a "proper" equals method.

@Override
public boolean equals(Object v){
   return (v instanceof BoolValue && ((BoolValue)v).item == this.item);
}

And when you override equals , you also need to override hashCode .

@Override
public int hashCode(){ return item ? 0 : 1; }

Finally (unless you intend to make these "values" mutable), since there are only two possible values, you should make the constructor private and provide the two values as static fields instead (you could also use an enum ).

public class BoolValue implements Value {
   private final boolean item;
   private BoolValue(boolean v){
      this.item = v;
   }
   public static final BoolValue TRUE = new BoolValue(true);
   public static final BoolValue FALSE = new BoolValue(false);
   public static BoolValue valueOf(boolean x){
     return x ? TRUE : FALSE;
   }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM