If it is a one-dimensional array of ordinary primitive type, you can copy it with clone (). If it is an array of classes, you can make a shallow copy by cloning (). Then, if it is a primitive type two-dimensional array ...
I used to make another two-dimensional array and copy the values, but when I saw someone's source, I thought I could write it in one line.
public static void main(String[] args) {
int[][] map = new int[3][3];
for (int y=0; y<3; y++) {
for (int x=0; x<3; x++) {
map[y][x] = x+y;
}
}
System.out.println("before");
for (int y=0; y<3; y++) {
for (int x=0; x<3; x++) {
System.out.print(map[y][x] + " ");;
}
System.out.println("");
}
int[][] nmap = map.clone();
for (int y=0; y<3; y++) {
for (int x=0; x<3; x++) {
nmap[y][x] = 4-(x+y);
}
}
System.out.println("after");
for (int y=0; y<3; y++) {
for (int x=0; x<3; x++) {
System.out.print(map[y][x] + " ");;
}
System.out.println("");
}
}
When you run
before
0 1 2
1 2 3
2 3 4
after
4 3 2
3 2 1
2 1 0
I intended to make clone () in nmap, but map has been rewritten.
Try to output the hash value of int [].
public static void main(String[] args) {
int[][] map = new int[3][3];
System.out.println("before");
for (int y=0; y<3; y++) {
System.out.println(map[y]);
}
int[][] nmap = map.clone();
System.out.println("after");
for (int y=0; y<3; y++) {
System.out.println(nmap[y]);
}
}
When you run
before
[I@15db9742
[I@6d06d69c
[I@7852e922
after
[I@15db9742
[I@6d06d69c
[I@7852e922
It's the same. If you think about it carefully, it's natural, but since int [] is a reference type, it is a shallow copy.
Then clone () int [].
public static void main(String[] args) {
int[][] map = new int[3][3];
System.out.println("before");
for (int y=0; y<3; y++) {
System.out.println(map[y]);
}
int[][] nmap = new int[3][];
for (int y=0; y<3; y++) {
nmap[y] = map[y].clone();
}
System.out.println("after");
for (int y=0; y<3; y++) {
System.out.println(nmap[y]);
}
}
When you run
before
[I@15db9742
[I@6d06d69c
[I@7852e922
after
[I@4e25154f
[I@70dea4e
[I@5c647e05
This time it's good.
Try clone () with int [].
public static void main(String[] args) {
int[][] map = new int[3][3];
for (int y=0; y<3; y++) {
for (int x=0; x<3; x++) {
map[y][x] = x+y;
}
}
System.out.println("before");
for (int y=0; y<3; y++) {
for (int x=0; x<3; x++) {
System.out.print(map[y][x] + " ");;
}
System.out.println("");
}
int[][] nmap = new int[3][];
for (int y=0; y<3; y++) {
nmap[y] = map[y].clone();
}
for (int y=0; y<3; y++) {
for (int x=0; x<3; x++) {
nmap[y][x] = 4-(x+y);
}
}
System.out.println("after");
for (int y=0; y<3; y++) {
for (int x=0; x<3; x++) {
System.out.print(map[y][x] + " ");;
}
System.out.println("");
}
}
When you run
before
0 1 2
1 2 3
2 3 4
after
0 1 2
1 2 3
2 3 4
nmap has a copy of the map.
Two-dimensional arrays cannot be clone () in one row. Even if you write it in someone's source, there is no guarantee that it is correct.
Recommended Posts