Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Operator '+' cannot be applied to 'int', 'java.lang.Object'

Tags:

java

arraylist

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();
    }
}
like image 580
wael jawadi Avatar asked May 15 '26 23:05

wael jawadi


1 Answers

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.

like image 77
vitalh Avatar answered May 19 '26 02:05

vitalh