Ex. 7/13 "Iterating over an ArrayList". No errors, just a question on theory


#1

https://www.codecademy.com/courses/learn-java/lessons/data-structures/exercises/arraylist-iterating?action=lesson_resume

Hello. My code runs fine. My question is basically: at line 14, why isn’t it

j <= weeklyTemperatures.size()

??

I mean, doesn’t

j < weeklyTemperatures.size()

imply that the code iterates up until the last entry in the array? as it’s not <=.



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

	}
}



#2

…is 1 less than the length due to zero-indexing.


#3

Aha, I see now: the array is zero-indexed, but arrayName.size() is measured normally, i.e zero is not included in the size of the list. Cool :slight_smile:


#4

Exactly. We count with natural numbers, and index with integers.


#5

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