gpt4 book ai didi

java - 如何交换两个整数包装器对象

转载 作者:行者123 更新时间:2023-11-30 07:29:52 26 4
gpt4 key购买 nike

如何交换两个 Integer 包装器的内容?

void swap(Integer a,Integer b){
/*We can't use this as it will not reflect in calling program,and i know why
Integer c = a;
a= b;
b = c;
*/
//how can i swap them ? Does Integer has some setValue kind of method?
//if yes
int c = a;
a.setValue(b);
b.setValue(c);

}

最佳答案

你不能,正是因为 Integer 是不可变的(以及其他原始包装器类型)。如果你有一个可变的包装类,那就没问题了:

public final class MutableInteger {
{
private int value;

public MutableInteger(int value) {
this.value = value;
}

public void setValue(int value) {
this.value = value;
}

public int getValue() {
return value;
}
}

void swap(MutableInteger a, MutableInteger b) {
int c = a.getValue();
a.setValue(b.getValue());
b.setValue(c);
}

但是,由于 Integer 中缺少与 setValue 等效的方法,因此基本上无法完成您的要求。 这是一件好事。这意味着对于大多数情况,我们可能希望将 Integer 值传递给另一个方法,我们不需要需要担心方法是否会改变它。不变性让您可以更轻松地推理您的代码,而无需仔细跟踪每个方法的作用,以防它更改您脚下的数据。

关于java - 如何交换两个整数包装器对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8238415/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com