如何交换两个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);
}
答案 0 :(得分:2)
你不能,因为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);
}
但是,由于setValue
中缺少Integer
的等价物,基本上没有办法做你所要求的。 这是一件好事。这意味着对于大多数案例,我们可能希望将Integer
值传递给其他方法,我们无需担心关于该方法是否会改变它。不变性使得推理代码变得容易得多,而不必仔细追踪每种方法的作用,以防万一它会改变您的数据。
答案 1 :(得分:1)
Java中的包装类型是不可变的,因此不提供setter方法。而Java则通过按值传递引用来工作。你能告诉我们你为什么要换东西吗?
答案 2 :(得分:1)
类型java.lang.Integer
表示永远不会更改其值的不可变数字。如果您需要可变号码,请尝试使用Apache Commons中的MutableInt
。
在Java中,与C ++相反,您无法将引用传递给任意内存位置,因此在大多数情况下无法进行交换。你能得到的最接近的是:
public static void swap(Integer[] ints, int index1, int index2) {
Integer tmp = ints[index1];
ints[index1] = ints[index2];
ints[index2] = tmp;
}
您可以使用List<T>
编写类似的代码,但是您总是需要一个容器(或两个)来交换东西。
答案 3 :(得分:0)
请参阅此文以明确Article
您将清楚地了解按值传递的传递及其概念
答案 4 :(得分:0)
class MyClass{
int a = 10 , b = 20;
public void swap(MyClass obj){
int c;
c = obj.a;
obj.a = obj.b;
obj.b = c;
}
public static void main(String a[]){
MyClass obj = new MyClass();
System.out.println("a : "+obj.a);
System.out.println("b : "+obj.b);
obj.swap(obj);
System.out.println("new a : "+obj.a);
System.out.println("new b : "+obj.b);
}
}
答案 5 :(得分:0)
public class NewInteger {
private int a;
private int b;
public int getA() {
return a;
}
public int getB() {
return b;
}
public NewInteger(int a, int b) {
this.a = a;
this.b = b;
}
public void swap(){
int c = this.a;
this.a = this.b;
this.b = c;
}
}
NewInteger obj = new NewInteger(1, 2);
System.out.println(obj.getA());
System.out.println(obj.getB());
obj.swap();
System.out.println(obj.getA());
System.out.println(obj.getB());
输出: 1 2 2 1