Home > Net >  Working on ArrayList in Java, I'm not sure why the loop isn't working
Working on ArrayList in Java, I'm not sure why the loop isn't working

Time:04-04

I'm trying to add 100 to each elements of the list using a for loop

I saved the desired values (from the list 100)to a variable a; then replace each element of the list using the index and the variable a;

List<Integer> numbers= new ArrayList<>();
        numbers.add(8);
        numbers.add(9);
        numbers.add(22);
        numbers.add(42);
        numbers.add(100);

for(int i=0;i<numbers.size();i  ){
            int a=numbers.get(i) 100;
            numbers.add(i,a);
       }

        System.out.println("The new elements of the list are "  numbers);

CodePudding user response:

According to the Javadoc for java.util.List, numbers.add(i,a) inserts a at index i. You should use numbers.set(i, a) instead since you don't want to insert new elements but replace existing ones.

CodePudding user response:

numbers.add(i,a) don't replace the element at position i. It inserts a new element at that position, thus increasing the size of the numbers array. Use the method numbers.set(i,a) instead

  • Related