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



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(2, 111);

		for (int j = 0; j < weeklyTemperatures.size(); j++){
      System.out.println( weeklyTemperatures.get(j) );



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


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:


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


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