nus-cs2113-AY2324S2 / forum

2 stars 0 forks source link

Autoboxing/ Unboxing in Wk6 "Weekly Roster" #21

Closed NGXZS closed 3 months ago

NGXZS commented 4 months ago
image

Hi all, would like to ask about autoboxing/ unboxing in Java.

The partial solution for Wk6 "Weekly Roster" has this line of code: Integer newValue = Integer.valueOf(roster.get(day).intValue() + 1);.

Would like to ask if we can just type: Integer newValue = roster.get(day) + 1; as Java does autoboxing/ unboxing for us (see https://www.geeksforgeeks.org/autoboxing-unboxing-java/).

Or is this a code standard thing?

Would appreciate any clarifications/ inputs, thank you!

ZMinghuiZ commented 4 months ago

Hi, I think this expression Integer newValue = roster.get(day) + 1; is ok. Since roster.get(day) would return a Integer instance and by adding 1, the integer instance is unboxed into int to perform the addition. When the addition result is assigned to newValue it is boxed into an Integer. These processes is done automatically by Java, which is equivalent to do Integer newValue = Integer.valueOf(roster.get(day).intValue() + 1); where u are boxing and unboxing manually.

okkhoy commented 4 months ago

You can use either of them; nothing to do with coding standards here :-)