-2

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?

Pedro Henrique
  • 609
  • 2
  • 9
  • 26
  • 1
    Problem is from your current position `i` you're adding the values of `register.get(i) + register.get(i+1)`, whereas `i` iterates through your whole collection. Ergo if your `i` has the index of the last item in the collection, `i+1` doesn't exist (out of bounds). I think it would suffice you let you for loop run through `i=0` to `i < register.size() - 1;`, but maybe you need to re-structure your logic a bit. – Maximilian Gerhardt Jan 28 '16 at 16:54
  • Have a look at using Comparators too. Then the next programmer to read your code won't pass out. https://docs.oracle.com/javase/7/docs/api/java/util/Comparator.html – riddle_me_this Jan 28 '16 at 16:56
  • 1
    Even if you fix the problem of indexing beyond the arraylist bounds, your algorithm is flawed. It will only combine same-spelling items that are adjacent. Try going through it by hand when the produce list id [Banana, berry, baNANA] – FredK Jan 28 '16 at 17:16

1 Answers1

0

You have three products.

Say if i = 2, then,

if ( register.get(i).getProduct().getNameOfProduct().equalsIgnoreCase(register.get(i+1).getProduct().getNameOfProduct()))

register.get(i) is fine, it has the index 2, the index of the last element. But register.get(i+1) is now one index passed the last element of the arraylist. That is, i+1 == register.size(). That's why you're getting an IndexOutOfBoundsException.

lightning_missile
  • 2,821
  • 5
  • 30
  • 58