Welcome to the Treehouse Community

Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.

Start your free trial

Android Android Lists and Adapters (2015) Updating the Data Model From JSONArray to a Java Array

Diego Marrs
Diego Marrs
8,243 Points

What do these lines of code do?

Hello,

I'm having trouble understanding what these lines of code do:

for (int i = 0; i < data.length(); i++)
days[i] = day;

Also, why did we put brackets around 'Day' and 'Hour' in the deceleration when making the methods? Finally, why do people commonly use 'i' when making a 'for loop'?

Please help!

1 Answer

Kourosh Raeen
Kourosh Raeen
23,733 Points

The for loop iterates over data which is an array of JSON objects. For each of these JSON objects the values for the keys "summary", "icon", "temperatureMax", and "time" are extracted and used to create an object of type Day, which is then added to the days array. The days array is an array of type Day which means that it is capable of holding objects of type Day. That is the reason in the declaration of the array you see Day followed by []. This is the same reason for seeing Day[] in the method declaration since the method returns an array of objects of type Day. For the same reason you see Hour[] in the declaration of the getHourlyForecast() method as this method returns an array of objects of type Hour.

As for the reason behind using i for a loop variable, see this link for some possible answers: https://www.quora.com/When-writing-a-for-loop-why-does-everyone-name-the-variable-as-i

Diego Marrs
Diego Marrs
8,243 Points

Thanks! But why did we create the int and increment it all in the 'for' loop's parentheses:

(int i = 0; i < data.length(); i++)

Couldn't we just do that in the for loop?

Kourosh Raeen
Kourosh Raeen
23,733 Points

Hi Diego - That's the typical way of setting up a for loop. If you use a while loop then you do the initialization of the loop variable and the incrementation inside the body of the loop. Take a look at this short page on the Java for statement: https://docs.oracle.com/javase/tutorial/java/nutsandbolts/for.html