所以给定一个数组的元素,我试图创建一个Location对象的arraylist,其中包含与给定位置相邻的所有元素(对角线和旁边,但不包括给定的位置)。 这是我的位置课程:
public class Location
{
// Row and column positions.
private int row;
private int col;
public Location(int row, int col)
{
this.row = row;
this.col = col;
}
//getRow() & getCol() methods not shown
以下是我试图在另一个类中完成的方法:
public List<Location> adjacentLocations(Location location)
{
List<Location> locations = new ArrayList<>();
//todo, diag, next
return locations
}
答案 0 :(得分:0)
为什么不直接将列表指定为ArrayList。 例如:
ArrayList<Location> locations = new ArrayList<>();
public ArrayList<Location> adjacentLocations(Location location)
{
locations.add(location);
}
public ArrayList<Location> getLocations()
{
for(int i = 0; i < locations.length; i++)
{
System.out.println(locations[i]);
}
}
答案 1 :(得分:0)
我假设有负坐标是无效的。
public List<Location> adjacentLocations(Location location)
{
List<Location> locations = new ArrayList<Location>();
// Calculate all the adjacent positions relative to the specified point.
int row = location.getRow();
int col = location.getCol();
for (int r = row -1; r<row +2; r++)
{
for (int c = col -1; c < col + 2; c++)
{
if ((c > -1 && r > -1) && !(r == row && c == col))
{
locations.add(new Location(r, c));
}
}
}
return locations;
}
填写课程以证明用法:
package stacktest;
import java.util.ArrayList;
import java.util.List;
public class Location {
// Row and column positions.
private int row;
private int col;
public Location(int row, int col)
{
this.row = row;
this.col = col;
}
public int getRow()
{
return this.row;
}
public int getCol()
{
return this.col;
}
public String toString()
{
return "[" + row + ", " + col + "]";
}
public List<Location> adjacentLocations()
{
List<Location> locations = new ArrayList<Location>();
// Calculate all the adjacent positions relative to the specified point.
for (int r = row -1; r<row +2; r++)
{
for (int c = col -1; c < col + 2; c++)
{
if ((c > -1 && r > -1) && !(r == row && c == col))
{
locations.add(new Location(r, c));
}
}
}
return locations;
}
public static void main(String[] args)
{
ArrayList<Location> originalLocations = new ArrayList<Location>();
originalLocations.add(new Location(4, 10));
originalLocations.add(new Location(100, 100));
originalLocations.add(new Location(1, 0));
for (Location l: originalLocations)
{
List<Location> adjacent = l.adjacentLocations();
System.out.println("orig: " + l);
for (Location adj: adjacent)
{
System.out.println(" -> " + adj);
}
}
}
}
输出:
orig: [4, 10]
-> [3, 9]
-> [3, 10]
-> [3, 11]
-> [4, 9]
-> [4, 11]
-> [5, 9]
-> [5, 10]
-> [5, 11]
orig: [100, 100]
-> [99, 99]
-> [99, 100]
-> [99, 101]
-> [100, 99]
-> [100, 101]
-> [101, 99]
-> [101, 100]
-> [101, 101]
orig: [1, 0]
-> [0, 0]
-> [0, 1]
-> [1, 1]
-> [2, 0]
-> [2, 1]
答案 2 :(得分:0)
如果我理解正确,您需要列出给定location[x][y]
的所有位置元素location[i][j]
,其中(x,y)
代表位置的{(i-1,j-1),(i+1,j+1),(i,j+1),(i+1,j),(i-1,j),(i,j-1),(i+1,j-1),(i-1,j+1)}
索引集对属于该集合
reloadData