简体   繁体   English

交换功能:Java按值传递密码失败

[英]Swapping function : Java Pass-By-Value code failed

 public void swap(Point var1, Point var2)
 {
  var1.x = 100;
  var1.y = 100;
  Point temp = var1;
  var1 = var2;
  var2 = temp;
 }

public static void main(String [] args)
{
  Point p1 = new Point(0,0);
  Point p2 = new Point(0,0);
  System.out.println("A: " + p1.x + " B: " +p1.y); 
  System.out.println("A: " + p2.x + " B: " +p2.y);
  System.out.println(" ");
  swap(p1,p2);
  System.out.println("A: " + p1.x + " B:" + p1.y); 
  System.out.println("A: " + p2.x + " B: " +p2.y);  
}

Running the code produces: 运行代码将产生:

A: 0 B: 0
A: 0 B: 0
A: 100 B: 100
A: 0 B: 0

I understand how the function changes the value of p1 as it is passed-by-value. 我了解该函数如何更改按值传递的p1的值。 What i dont get is why the swap of p1 and p2 failed. 我没有得到的是为什么p1和p2交换失败。

Java is pass by value at all times . Java是由价值在任何时候通过。 That's the only mechanism for both primitives and objects. 两个基本类型和对象的唯一机制。

The key is to know what's passed for objects. 关键是要知道对象传递了什么。 It's not the object itself; 这不是对象本身;而是对象本身。 that lives out on the heap. 生活在堆上。 It's the reference to that object that's passed by value. 它是对按值传递的对象的引用

You cannot modify a passed reference and return the new value to the caller, but you can modify the state of the object it refers to - if it's mutable and exposes appropriate methods for you to call. 您不能修改传递的引用并将新值返回给调用者,但是可以修改其引用的对象的状态-如果该对象可变,并公开了适合您调用的方法。

The class swap with pointers, similar to what's possible with C, doesn't work because you can't change what the passed reference refers to and return the new values to the caller. 类似于C的可能,带有指针的类交换不起作用,因为您无法更改传递的引用所引用的内容,也无法将新值返回给调用者。

myFunction()刚换到里面的函数的两个对象(这是从外面那些不同)的引用,但换的功能,也没有对象实例本身之外的参考!

在正式参数位置将生成一个引用的副本,因此将有一个指向Point实例的新引用

Objects are assigned by reference, not cloned, but the arguments stay as references to the actual objects, they will not turn into "references to references". 对象是通过引用分配的,不是克隆的,但参数保留为对实际对象的引用,它们不会变成“对引用的引用”。

What I mean is that var1 reference the same object as p1 initially, but then you change var1 to reference another object. 我的意思是, var1最初引用的对象与p1相同,但是随后您将var1更改为引用另一个对象。 This does not affect what object p1 references because var1 is NOT a reference to p1 , only a reference to the same object as p1 is referencing. 这并不影响什么对象p1引用,因为var1不是一个参考p1 ,只有同一个对象作为参考p1被引用。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM