7/13 Relationship between Get method and Arguments?



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(2, 111);
         for (int j = 0; j < weeklyTemperatures.size(); j++) {
       System.out.println( weeklyTemperatures.get(j));



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.


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


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