1

I am trying to get the sum of all the byte arraylist from position 1 to end when i try to add i get error as "The operator + is undefined for the argument type(s) int, Object"

I have a finalbyte arraylist

ArrayList finalbyte = new ArrayList();
    finalbyte.add(A);
    finalbyte.add(B);
    finalbyte.add(C);
    finalbyte.add(D);

Am adding each value from different sources and the output of Syso looks like {67,8,1,-25,4,2,2,2,2}, the values are different for each run.Now am trying to add these values from {8,1,-25,4,2,2,2,2} 1st till the end position.

    for(int i=0;i<finalbyte.size();i++) {
    System.out.println(""+finalbyte.get(i));
    value=value+finalbyte.get(i);
    }

I want sum, value= {from 1st + end of byte list} and finalbyte.add(value); how can i add byte array values and add it back again to the bytearray list?

tester
  • 21
  • 1

1 Answers1

3

It doesn't understand what type finalbyte is. Much of the time this would have been more obvious but what you were doing requires that it knows that it needs two integers to add, not an integer an "Object"

There are two ways you could tell the compiler that it's an Integer--You can cast it when you get it out:

... +(Integer)finalbyte.get(i);

Or you can use generics when you declare it (BY FAR the better solution):

ArrayList<Integer> finalbyte = new ArrayList<>();

Once the compiler knows it's an Integer, it can properly auto-unbox the integer to an int, then + will work.

Note that your other operation worked because adding strings together actually uses the .toString() method--a method defined on "Object" itself so that it's always available.

Bill K
  • 62,186
  • 18
  • 105
  • 157