1 public class Horse { 2 Horse same; 3 String jimmy; 4 5 public Horse(String lee) { 6 jimmy = lee; 7 } 8 9 public Horse same(Horse horse) { 10 if (same != null) { 11 Horse same = horse; 12 same.same = horse; 13 same = horse.same; 14 } 15 return same.same; 16 } 17 18 public static void main(String[] args) { 19 Horse horse = new Horse("youve been"); 20 Horse cult = new Horse("horsed"); 21 cult.same = cult; 22 cult = cult.same(horse); 23 System.out.println(cult.jimmy); 24 System.out.println(horse.jimmy); 25 } 26 }
输出的结果是
horsed youve been
原因在于,在第14行结束后,局部变量same(就是指向horse的那个same)就被销毁了,此时15行的same是cult 的same, return same.same 就是return cult自己。
1 public class Foo { 2 public int x, y; 3 public Foo (int x, int y) { 4 this.x = x; 5 this.y = y; 6 } 7 8 public static void switcheroo (Foo a, Foo b) { 9 Foo temp = a; 10 a = b; 11 b = temp; 12 } 13 14 public static void fliperoo (Foo a, Foo b) { 15 Foo temp = new Foo(a.x, a.y); 16 a.x = b.x; 17 a.y = b.y; 18 b.x = temp.x; 19 b.y = temp.y; 20 } 21 22 public static void swaperoo (Foo a, Foo b) { 23 Foo temp = a; 24 a.x = b.x; 25 a.y = b.y; 26 b.x = temp.x; 27 b.y = temp.y; 28 } 29 30 public static void main (String[] args) { 31 Foo foobar = new Foo(10, 20); 32 Foo baz = new Foo(30, 40); 33 switcheroo(foobar, baz); //foobar.x: ___ foobar.y: ___ baz.x: ___ baz.y: ___ 34 fliperoo(foobar, baz); //foobar.x: ___ foobar.y: ___ baz.x: ___ baz.y: ___ 35 swaperoo(foobar, baz); //foobar.x: ___ foobar.y: ___ baz.x: ___ baz.y: ___ 36 System.out.println(); 37 } 38 }
10 20 30 40
30 40 10 20
10 20 10 20
33 行我有点不太明白。
其实传入到函数Switcheroo的时候,a 和 b 都仅仅是指向foobar and baz,所以 a = b 就仅仅只是改变了a 的指向罢了,从指向foobar 到指向 baz.
标签:week2,CS61B,baz,same,foobar,discussion3,___,Foo,public From: https://www.cnblogs.com/xuenima/p/17379329.html