Ex 8.13: Why "Integer" and not "int" in ArrayLists<>?


#1

https://www.codecademy.com/courses/learn-java/lessons/data-structures/exercises/for-each-loop?action=lesson_resume

Why does the code suddenly label integers with Integer? before we had just used int. Is it because it’s a peculiarity within ArrayLists?


//Example code:

for (Integer temperature : weeklyTemperatures) {
    System.out.println(temperature);
}



#2

int is a type, Integer is a class (loosely speaking).


#3

Ah, as seen in its capitalisation, similar to uses of “String”. But why are we suddenly creating a variable within a class Integer, rather than denoting it with the primitive datatype int? By not denoting its type, are we creating a typeless variable? Isn’t that illegal?


#4

There are some good answers in this SERP:

https://www.startpage.com/do/dsearch?query=java+int+vs+Integer


#5

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