7/13 Relationship between Get method and Arguments?

<PLEASE USE THE FOLLOWING TEMPLATE TO HELP YOU CREATE A GREAT POST!>

<Below this line, add a link to the EXACT exercise that you are stuck at.>
https://www.codecademy.com/courses/learn-java/lessons/data-structures/exercises/arraylist-iterating?action=lesson_resume&link_content_target=interstitial_lesson

Hey All, I just have a general question about the get method. The exercise wouldn’t let me pass until I added the argument j to the get method, but isn’t j just serving as a counter for the ‘for’ loop? Why does it affect what indices are being accessed?

```

import java.util.ArrayList;

public class TemperaturesC {

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);

     for (int j = 0; j < weeklyTemperatures.size(); j++) {

   System.out.println( weeklyTemperatures.get(j));
     }
}

}

<do not remove the three backticks above>

Hey,

You’re right in that j serves as a counter, but there’s a little more to it than that.

j in this scenario on each iteration will produce numbers 0 -> 4.

So every time you call weeklyTemperatures.get(j) you’re accessing the index that relates to the value of j at that point in time.

So really j is serving as two purposes. It’s figuring out how many times to index over the Array as well as giving the current index to a print statement so that it can display the value stored in the index.

2 Likes

Ah, I see. It makes sense now. Thank you!

1 Like

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