Skip to content

Instantly share code, notes, and snippets.

@mdstoy
Last active June 7, 2019 09:54
Show Gist options
  • Save mdstoy/ae072f35aece925fd6031784086f18cf to your computer and use it in GitHub Desktop.
Save mdstoy/ae072f35aece925fd6031784086f18cf to your computer and use it in GitHub Desktop.
「もう参照渡しとは言わせない 2018 冬」用 サンプルコード
import java.util.*;
public class R {
public static void main(String[] args) {
List<String> x = new ArrayList<>();
System.out.printf("x: %s\n", x); // "x: []"
add(x);
System.out.printf("x: %s\n", x); // "x: ["xxx"]"
}
public static void add(List<String> a) {
a.add("xxx");
}
}
// pseudocode
swap(int a, int b) {
int tmp = a
a = b
b = tmp
}
x = 1
y = 2
swap(x, y)
// x = 2, y = 1
import java.util.*;
public class Reference {
public static void main(String[] args) {
List<String> x = List.of("aaa");
List<String> y = List.of("bbb");
System.out.printf("x: %s, y: %s\n", x, y); // "x: ["aaa"], y: ["bbb"]"
swap(x, y);
System.out.printf("x: %s, y: %s\n", x, y); // "x: ["aaa"], y: ["bbb"]"
}
public static void swap(List<String> a, List<String> b) {
List<String> tmp = a;
a = b;
b = tmp;
}
}
// pseudocode
swap(int a, int b) {
int tmp = a
a = b
b = tmp
}
x = 1
y = 2
swap(x, y)
// x = 1, y = 2
public class Value {
public static void main(String[] args) {
int x = 1;
int y = 2;
System.out.printf("x: %d, y: %d\n", x, y); // "x: 1, y: 2"
swap(x, y);
System.out.printf("x: %d, y: %d\n", x, y); // "x: 1, y: 2"
}
public static void swap(int a, int b) {
int tmp = a;
a = b;
b = tmp;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment