class fuck { public fuck() { a = this.a; b = this.b;
} public int a = 3; public int b = 4;
}public class TestArg { public static void main(String[] args) { fuck f = new fuck(); System.out.println(f.a); System.out.println(f.b); swap(f); System.out.println(f.a); System.out.println(f.b);
}
public static void swap(fuck x) { int temp; temp = x.a; x.a = x.b; x.b = temp; } } 希望对你有帮助
假设在上面得代码中加入: /////////// ...... //// MyClassTest c = new MyClassTest(1); MyClassTest d = new MyClassTest(2); System.out.println(c); System.out.println(d); swap(c,d); System.out.println(c); System.out.println(d); /////// ...... ////// public static void swap(MyClassTest c1,MyClassTest c2){ c1.i ++; c2.i ++; MyClassTest temp = c1; c2 = c1; c1 = temp;
} class MyClassTest{ int i; public MyClassTest(int i){ this.i = i; } public String toString(){ return i +""; } } 当然,交换是不成功的.但是,应该注意到c和d的值均发生了变化。 那么,这里到底传的什么???
特殊问题特殊解决,只能这样假换址,(实值换内容量的值)。 public class Int { int i; private void setI(int _i) { this.i = _i; } public Int(int _i) { this.i = _i; } private int getI() { return this.i; } public void swap(Int I) { int _i = I.getI(); I.setI(this.getI()); this.setI(_i); } public String toString() { return String.valueOf(i); } }如果你不是碰到这样的问题要解决,用不着在这钻牛角。
我想让这个,a与b交换值,i与j交换值,
哪位高手还有办法?
{
public fuck()
{
a = this.a;
b = this.b;
}
public int a = 3;
public int b = 4;
}public class TestArg
{
public static void main(String[] args)
{
fuck f = new fuck();
System.out.println(f.a);
System.out.println(f.b);
swap(f);
System.out.println(f.a);
System.out.println(f.b);
}
public static void swap(fuck x)
{
int temp;
temp = x.a;
x.a = x.b;
x.b = temp;
}
}
希望对你有帮助
所以,你不要再尝试了:)。
public static void swap(Integer ia, Integer ib)
{
Integer temp = ia;
ia = ib;
ib = temp;
}
但是你这种更换其实是已经改变了ia,ib所指向的地址了,而不是改变内容!
Java里面是不允许作出这样的改变的,你只能够通过其他的一些方法间接实现
///////////
......
////
MyClassTest c = new MyClassTest(1);
MyClassTest d = new MyClassTest(2);
System.out.println(c);
System.out.println(d);
swap(c,d);
System.out.println(c);
System.out.println(d);
///////
......
//////
public static void swap(MyClassTest c1,MyClassTest c2){
c1.i ++;
c2.i ++;
MyClassTest temp = c1;
c2 = c1;
c1 = temp;
} class MyClassTest{
int i;
public MyClassTest(int i){
this.i = i;
}
public String toString(){
return i +"";
}
}
当然,交换是不成功的.但是,应该注意到c和d的值均发生了变化。
那么,这里到底传的什么???
public class Int
{
int i; private void setI(int _i)
{
this.i = _i;
} public Int(int _i)
{
this.i = _i;
} private int getI()
{
return this.i;
} public void swap(Int I)
{
int _i = I.getI();
I.setI(this.getI());
this.setI(_i);
} public String toString()
{
return String.valueOf(i);
}
}如果你不是碰到这样的问题要解决,用不着在这钻牛角。
对于primative类型,传送的是value
对于object,传送的是reference value请注意了:无乱primative还是object,传送的都是value。
所以,各位的想法都偏了。你只可能利用一些技巧达到传址的目的。但不可能得到Java语言本身机制上的支持。