I have a method that compare the name of two products in an arraylist, this is the method:
public void compareNames(ArrayList<Register> register) {
Register registerNew = null;
Product productNew = null;
int sumEqualProducts =0;
for (int i = 0; i <register.size() ; i++) {
if ( register.get(i).getProduct().getNameOfProduct().equalsIgnoreCase(register.get(i+1).getProduct().getNameOfProduct())) {
sumEqualProducts = register.get(i).getQuantity() + register.get(i + 1).getQuantity();
register.remove(i+1);
productNew = new Product(register.get(i).getProduct().getNameOfProduct(), register.get(i).getProduto().getUnitValue());
registerNew = new Register(productNew, sumEqualProducts);
register.set(i, registerNew);
}
}
}
On the arraylist, I have 3 products, [Banana,baNANA,berry]. For the firts 2 index(Banana, baNANA), it's working as expected, the if is comparing the name of products and editing the value of index, with a new that have the sum of the 2 products with same name... But, when the comparison is between Banana and berry, the if is returning true, but should be false, because the values are not equal. Also, I'm getting this error:
java.lang.IndexOutOfBoundsException: Index: 2, Size: 2
How can I fix this comparison?