ArrayList: Insertion problem


#1

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(78);
	weeklyTemperatures.add(67);
	weeklyTemperatures.add(89);
	weeklyTemperatures.add(94);

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.


#2

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.


#3

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(Variable);
 ArrayList.add(indexofVariable, Variable)

Hope this gave you a more depth Anwser! Thanks


#4

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