I think this question is related to this question: Is Java "pass-by-reference" or "pass-by-value"?, but not really the same.
Suppose I have this loop code:
ArrayList<foo> list = new ArrayList<foo>();
Calendar cal = Calendar.getInstance();
for(int i = 0; i < 10; ++i) {
cal.set(Calendar.HOUR, i);
list.add(new foo(cal));
}
for(int i = 0; i < 10; ++i) {
System.out.print(list.get(i).calToString());
}
foo.class:
public class foo {
private Calendar mCal;
public foo(Calendar cal) {
mCal = cal;
}
public String calToString() {
return String.valueOf(mCal.get(Calendar.HOUR));
}
}
The resulting list has all its items Calendar.HOUR
set to 9
. It prints 9999999999
. How can I make it so that each item will have 0-9 respectively? Will instantiating variable cal
inside the loop be a performance issue (if in case foo
is a more complex class)?