我有一個看起來像這樣的二維陣列:
1 1 1 1
1 1 1 1
1 1 1 1
0 1 1 1
我想在一個稱為鄰居的ArrayList 中存盤正確的 0 值。但是,如果我呼叫
neigbors.add(location[4][1])
我會得到值“1”,插入(4,1)。有什么辦法可以做到嗎?讓我提一下我使用這些變數:
List<Integer> neighbors = new ArrayList<Integer>();
int[][] locations = new int[5][5];
uj5u.com熱心網友回復:
您應該使用像 Point 這樣的內置 Java 類。
List<Point> neighbors = new ArrayList<>();
然后當你添加一個點時:
neighbors.add( new Point( 4, 1) );
你可以用。
List<int[]> neighbors = new ArrayList<>();
然后
neighbors.add( new int[]{ 4, 1} );
您應該使用 java 類或創建自己的類的原因是它具有有意義的 hashCode 和 equals 方法。此外,不能保證串列中的 int[] 有 2 個元素。
uj5u.com熱心網友回復:
您可以創建一個Point存盤其 x 和 y 坐標的類。
import java.util.Objects;
public class Point {
private final int x, y;
public Point(int x, int y) {
this.x = x;
this.y = y;
}
public int getX() {
return x;
}
public int getY() {
return y;
}
@Override
public String toString() {
return "Point [x=" x ", y=" y "]";
}
@Override
public int hashCode() {
return Objects.hash(x, y);
}
@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
Point other = (Point) obj;
return x == other.x && y == other.y;
}
}
然后,你可以創建一個List的Point秒。
List<Point> points = new ArrayList<>();
points.add(new Point(4, 1));
轉載請註明出處,本文鏈接:https://www.uj5u.com/gongcheng/383242.html
