日期:2014-05-20  浏览次数:20711 次

菜鸟求助,Java中传值还是传引用?
请解释一下,为什么tripleSalary(harry)使得harry的工资是原来的3倍,
而在执行完swap(a,b)函数后并没有使原先指向Alice的a指向Bob呢?

public class ParamTest
{
  public static void main(String[] args)
  {
  Employee harry = new Employee("Harry", 50000);
  System.out.println("Before: salary=" + harry.getSalary());
  tripleSalary(harry);
  System.out.println("After: salary=" + harry.getSalary());

  Employee a = new Employee("Alice", 70000);
  Employee b = new Employee("Bob", 60000);
  System.out.println("Before: a=" + a.getName());
  System.out.println("Before: b=" + b.getName());
  swap(a, b);
  System.out.println("After: a=" + a.getName());
  System.out.println("After: b=" + b.getName());
  }

  public static void tripleSalary(Employee x) // works
  {
  x.raiseSalary(200);
  System.out.println("End of method: salary="
  + x.getSalary());
  }

  public static void swap(Employee x, Employee y)
  {
  Employee temp = x;
  x = y;
  y = temp;
  System.out.println("End of method: x=" + x.getName());
  System.out.println("End of method: y=" + y.getName());
  }
}

class Employee // simplified Employee class
{
  public Employee(String n, double s)
  {
  name = n;
  salary = s;
  }

  public String getName()
  {
  return name;
  }

  public double getSalary()
  {
  return salary;
  }

  public void raiseSalary(double byPercent)
  {
  double raise = salary * byPercent / 100;
  salary += raise;
  }

  private String name;
  private double salary;
}


------解决方案--------------------


看到了吗,x,y的指向改变了
但不会改变a,b的指向,
a,b还是指向了原来的对象。

遇到这种传值的问题最好画个内存图,
很明了清晰,不要看着程序想。

java中只有值传递,引用传递本质上也是值传递
叫法不同是为了区分传的是值还是引用

至于工资三倍的问题,楼主仔细看看题就知道了
raise = salary * byPercent / 100;
salary += raise; 
==>
salary += salary * byPercent / 100;(byPercent传的是200)
==>
salary = salary + salary * byPercent / 100;
==>
salary = salary * (1 + 2)