温馨提示×

温馨提示×

您好,登录后才能下订单哦!

密码登录×
登录注册×
其他方式登录
点击 登录注册 即表示同意《亿速云用户服务条款》

在Java中交换对象数据的方法

发布时间:2020-08-20 15:15:33 来源:亿速云 阅读:208 作者:小新 栏目:编程语言

这篇文章主要介绍在Java中交换对象数据的方法,文中介绍的非常详细,具有一定的参考价值,感兴趣的小伙伴们一定要看完!

                                                           假设我们有一个名为“Car”的类,它具有一些属性。我们创建了Car的两个对象,car1和car2,如何交换car1和car2的数据?

一个简单的解决方案是交换成员。例如,如果类Car只有一个integer(整数)属性“no”(Car number),我们可以通过简单地交换两辆车的成员来交换汽车。

class Car 
{ 
    int no; 
    Car(int no) { this.no = no; } 
} 
  
class Main 
{  
    public static void swap(Car c1, Car c2) 
    { 
        int temp = c1.no; 
        c1.no = c2.no; 
        c2.no = temp; 
    } 
    
    public static void main(String[] args) 
    { 
        Car c1 = new Car(1); 
        Car c2 = new Car(2); 
        swap(c1, c2); 
        System.out.println("c1.no = " + c1.no); 
        System.out.println("c2.no = " + c2.no); 
    } 
}

输出:

c1.no = 2
c2.no = 1

如果我们不知道Car的成员呢?

上面的解决方案是有效的,因为我们知道Car中有一个成员“no”。如果我们不知道Car的成员或者成员列表太大怎么办。这是一种非常常见的情况,因为使用其他类的类可能无法访问其他类的成员。下面的解决方案有效吗?

class Car 
{ 
    int model, no; 
  
    Car(int model, int no) 
    { 
        this.model = model; 
        this.no = no; 
    } 
  
    void print() 
    { 
        System.out.println("no = " + no + 
                           ", model = " + model); 
    } 
} 
  
class Main 
{ 
    public static void swap(Car c1, Car c2) 
    { 
        Car temp = c1; 
        c1 = c2; 
        c2 = temp; 
    } 
  
    public static void main(String[] args) 
    { 
        Car c1 = new Car(101, 1); 
        Car c2 = new Car(202, 2); 
        swap(c1, c2); 
        c1.print(); 
        c2.print(); 
    } 
}

输出:

no = 1, model = 101
no = 2, model = 202

从上面的输出中我们可以看到,没有交换对象。参数在Java中是通过值传递的。因此,当我们将c1和c2传递给swap()时,swap()函数会创建这些引用的副本。

解决方案是使用Wrapper类如果我们创建一个包含Car引用的包装类,我们可以通过交换Wrapper类的引用来交换Car。

class Car 
{ 
    int model, no; 
  
    Car(int model, int no) 
    { 
        this.model = model; 
        this.no = no; 
    } 
  
    void print() 
    { 
        System.out.println("no = " + no +  
                           ", model = " + model); 
    } 
} 
  
class CarWrapper 
{ 
   Car c; 
  
   CarWrapper(Car c)   {this.c = c;} 
} 
  
class Main 
{ 
    public static void swap(CarWrapper cw1,  
                            CarWrapper cw2) 
    { 
        Car temp = cw1.c; 
        cw1.c = cw2.c; 
        cw2.c = temp; 
    } 
  
    public static void main(String[] args) 
    { 
        Car c1 = new Car(101, 1); 
        Car c2 = new Car(202, 2); 
        CarWrapper cw1 = new CarWrapper(c1); 
        CarWrapper cw2 = new CarWrapper(c2); 
        swap(cw1, cw2); 
        cw1.c.print(); 
        cw2.c.print(); 
    } 
}

输出:

no = 2, model = 202
no = 1, model = 101

因此,即使user 类无法访问要交换对象的类的成员,Wrapper类解决方案仍然有效。

以上是在Java中交换对象数据的方法的所有内容,感谢各位的阅读!希望分享的内容对大家有帮助,更多相关知识,欢迎关注亿速云行业资讯频道!

向AI问一下细节

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

AI