I've just start learning how to manipulate array list.
I have a little probleme while counting the sum of myArray ------> the error is Operator '+' cannot be applied to 'int', 'java.lang.Object'
public static void main(String[] args) {
SpringApplication.run(DemoApplication.class, args);
ArrayList<Integer> myArray = new ArrayList<Integer>();
myArray.add(6);
myArray.add(2);
myArray.add(1);
int x = 0;
Iterator myIterator = myArray.iterator();
while (myIterator.hasNext()){
System.out.println(myIterator.next());
x = x + myIterator.next();
}
}
Iterator should be parameterized. Without specifying the Integer type, the compiler assumes java.lang.Object type to which the operator + is not applied.
Iterator<Integer> myIterator = myArray.iterator();
Technically, the + operator does not apply to objects other than String, but Integer is a wrapper class for primitive type int.
So, in this case, the compiler applies unboxing to get int, in which the + operator is defined.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With