/**
* @program: sixiang
* @description
* @author: wenwen
* @create: 2021-07-07 21:44
**/
//实现交换两个变量的值,要求:需要交换实参的值
class MyValue{
private int val;
public int getVal() {
return val;
}
public void setVal(int val) {
this.val = val;
}
}
public class changeShican {
public static void swap(MyValue myValue1,MyValue myValue2){
int temp = myValue1.getVal();
myValue1.setVal(myValue2.getVal());
myValue2.setVal(temp);
}
public static void main(String[] args) {
MyValue myValue1 = new MyValue();
myValue1.setVal(10);
MyValue myValue2 = new MyValue();
myValue2.setVal(20);
System.out.print(myValue1.getVal()+" "+myValue2.getVal());
swap(myValue1,myValue2);
System.out.print(myValue1.getVal()+" "+myValue2.getVal());
}
}
/**
* @program: sixiang
* @description
* @author: wenwen
* @create: 2021-07-07 21:44
**/
//实现交换两个变量的值,要求:需要交换实参的值
class MyValue{
public int val;
public int getVal() {
return val;
}
public void setVal(int val) {
this.val = val;
}
}
public class changeShican {
// public static void swap(MyValue myValue1,MyValue myValue2){
// int temp = myValue1.getVal();
// myValue1.setVal(myValue2.getVal());
// myValue2.setVal(temp);
//
//
// }
//
// public static void main(String[] args) {
// MyValue myValue1 = new MyValue();
// myValue1.setVal(10);
//
// MyValue myValue2 = new MyValue();
// myValue2.setVal(20);
//
// System.out.print(myValue1.getVal()+" "+myValue2.getVal());
// swap(myValue1,myValue2);
// System.out.print(myValue1.getVal()+" "+myValue2.getVal());
//
//
//
// }
public static void swap(MyValue myValue1,MyValue myValue2){
int temp = myValue1.val;
myValue1.val = myValue2.val;
myValue2.val = temp;
}
public static void main(String[] args) {
MyValue myValue1 = new MyValue();
myValue1.val=10;
MyValue myValue2 = new MyValue();
myValue2.val=20;
swap(myValue1,myValue2);
System.out.print(myValue1.val+" "+myValue2.val);
}
}
图解

这篇博客展示了如何在Java中交换两个对象属性的值,通过创建一个临时变量实现值的交换。代码示例中定义了MyValue类并实现了交换方法,最后在主函数中验证了交换操作。这种方法避免了直接修改对象的引用,确保了实参值的交换。
595

被折叠的 条评论
为什么被折叠?



