[英]Java “pass-by-value” in a loop
I think this question is related to this question: Is Java "pass-by-reference" or "pass-by-value"? 我认为这个问题与以下问题有关: Java是“按引用传递”还是“按值传递”? , 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: 让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
. 结果列表将其所有项目
Calendar.HOUR
设置为9
。 It prints 9999999999
. 它打印
9999999999
。 How can I make it so that each item will have 0-9 respectively? 如何使每个项目分别具有0-9? Will instantiating variable
cal
inside the loop be a performance issue (if in case foo
is a more complex class)? 在循环内部实例化变量
cal
是否会成为性能问题(如果foo
是更复杂的类)?
Actually you are overwriting your object, you declared it outside the loop and you keep changing it's value. 实际上,您正在覆盖对象,在循环之外声明了该对象,并不断更改其值。
You should create new instance inside the loop. 您应该在循环内创建新实例。 No, you won't notice any performance issues.
不,您不会注意到任何性能问题。
You would need to initialize a new Calendar
for each iteration of your loop. 您需要为循环的每次迭代初始化一个新的
Calendar
。
Something like: 就像是:
for(int i = 0; i < 10; ++i) {
Calendar cal = Calendar.getInstance();
Otherwise, the same instance is referenced everytime. 否则,每次都引用同一实例。
Therefore, the set
invocation modifies the same Calendar
, which is why you are getting all 9
s. 因此,
set
调用会修改相同的Calendar
,这就是为什么要获得所有9
s的原因。
More elegantly perhaps, you could initialize your Foo
class with a constructor taking the actual hour int
. 也许更优雅一些,您可以使用实际小时数为
int
的构造函数初始化Foo
类。
Then you would change Foo
to have its own Calendar
instance. 然后,您可以将
Foo
更改为具有自己的Calendar
实例。
class Main 主班
{ public static void main(String[] args) { {public static void main(String [] args){
ArrayList<foo> list = new ArrayList<foo>();
Calendar cal = null;
for (int i = 0; i < 10; ++i) {
cal=Calendar.getInstance();
cal.set(Calendar.HOUR, i);
list.add(new foo(cal));
}
for (int i = 0; i < 10; ++i) {
System.out.print(list.get(i).calToString());
}
}
} }
class foo { private Calendar mCal; class foo {private Calendar mCal;
public foo(Calendar cal) {
mCal = cal;
}
public String calToString() {
return String.valueOf(mCal.get(Calendar.HOUR));
}
} }
you are overwriting your calender object 您正在覆盖您的日历对象
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.