ArrayList: Insertion problem

Where is my current code:
import java.util.ArrayList;

public class TemperaturesB {

public static void main(String[] args) {

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

weeklyTemperatures.add(2, 111);

System.out.println( weeklyTemperatures.get(2) );



I cant figure out how to fix it after looking at it for about 10 minutes as well as looking on the forums. Any help would be great.

By adding a new value to the array 89 and 94 indexes got shifted by one. Your array looks like this: { 78, 67, 111, 89, 94 }. The print statement clearly outputs the wrong number.

Since you added the 111 number to the 2nd index moving every number to the right of index except first one. So it printed the wrong number.

Constructors for .add() method
 ArrayList.add(indexofVariable, Variable)

Hope this gave you a more depth Anwser! Thanks

1 Like

This topic was automatically closed 7 days after the last reply. New replies are no longer allowed.