Created
March 23, 2015 05:37
-
-
Save anonymous/d57d272579079b4e9ee8 to your computer and use it in GitHub Desktop.
Java Swap
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
class A { | |
private String name = null; | |
public A(String newName) { | |
name = newName; | |
} | |
public void Assign(A other) { | |
name = other.name; | |
} | |
public void SayHi() { | |
System.out.println("Hello from " + name); | |
} | |
} | |
class TestSwap { | |
public static void swap(A a1, A a2) { | |
A temp = new A(""); | |
temp.Assign(a1); | |
a1.Assign(a2); | |
a2.Assign(temp); | |
} | |
public static void setA3ByValue() { | |
A a1 = new A("Dog"); | |
A a2 = new A("Cat"); | |
A a3 = new A(""); | |
a3.Assign(a1); | |
swap(a1,a2); | |
a1.SayHi(); | |
a2.SayHi(); | |
a3.SayHi(); | |
} | |
public static void setA3ByReference() { | |
A a1 = new A("Dog"); | |
A a2 = new A("Cat"); | |
A a3 = a1; | |
swap(a1,a2); | |
a1.SayHi(); | |
a2.SayHi(); | |
a3.SayHi(); | |
} | |
public static void main(String[] args) { | |
setA3ByValue(); | |
setA3ByReference(); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment