简体   繁体   中英

compare two objects whether they are equals:

I have a list with two Box objects which are not the same (They have differ in id, address, quantity) and I need to get the index of the last item in the list which is 1 but I am always getting that the both objects are equal and the index of the last object is 0 and not 1 :

Why are the both objects the same and how to get the index of the last box in the list? Am I missing something?

System.out.println("##--## boxList size:  " + boxList.size());
if( boxList.get(0).equals(boxList.get(1))){
    System.out.println("##--## the both boxes are equals");
}

for(Box boxB: boxList){
    System.out.println("##--## boxB id: " + boxB.id + " box address: " + boxB.store.address + " ,box quantity: " + boxB.quantity + " x: " + boxList.indexOf(boxB));         
}

Box lastFirstLoop = boxList.get(1);
int indexTemp = boxList.indexOf(lastFirstLoop); 
System.out.println("##--## indexTemp: " + indexTemp );  

The output is:

##--## boxList size: 2
##--## the both boxes are equals
##--## boxB id: 1513682911061 box address: DS/1-1-1-1/A ,box quantity: 120 x: 0
##--## boxB id: 1513682911062 box address: DS/1-1-2-1/A ,box quantity: 18 x: 0
##--## indexTemp: 0

Edit:

@Override
public boolean equals(final Object other) {
    if (!(other instanceof Box)) {
        return false;
    }
    return new EqualsBuilder().appendSuper(super.equals(other)).isEquals();
}


/**
 * {@inheritDoc}
 */
@Override
public int hashCode() {
    if (this.hashCode == 0) {
        this.hashCode = new HashCodeBuilder().appendSuper(super.hashCode()).toHashCode();
    }
    return this.hashCode;
}

Assuming the "Box" is your custom class you should take a look here: https://stackoverflow.com/a/27609/6705466

It guides how to override equals(Object o) and hashCode(). You always should override those both together, and whenever equals returns true the hashCode should be the same.

My other suggestion is, add a little if statement before accessing index in the list (Just to avoid IndexOutOufBoundsException, possibly null check would be a nice to have)

First of all you need to **Override** your equals() method since **Box** is your Custom class. If you want to use .equals() method properly. Example is shown below: 

    class Box {
    /*your class body*/

    // Overriding equals() to compare two Box objects
    @Override
    public boolean equals(Object o) {
        Box box = (Box) o;
        if(id.equals(box.id)){
            return true;
        }
        return false;
    }
    }

And for indexOf() method you need to override hashCode() method.Shown below:

@Override
public int hashCode() {
   return Objects.hash(id);
}

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