你经常会遇到同样的问题:如何将二维数组视为一维数组进行操作。我写了一个通用类Grid,可以通过索引或(x,y)来访问对象。
看下面的类并理解其中的思想。:)
你可以使用以下类来作为二维数组或一维数组进行数据操作。这是我编写和使用的代码。
import java.util.List;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Iterator;
public class Grid<E>
{
private int size ;
private int width ;
private int height ;
private List<E> elements;
public int getCapacity()
{
return getWidth() * getHeight();
}
public int getSize()
{
return getElements().size();
}
public Grid(int sideSize)
{
this(sideSize,sideSize);
}
public Grid(int width, int height)
{
this.width = width ;
this.height = height;
this.elements = new ArrayList<E>(
Collections.nCopies(width*height, (E)null));
}
public int getHeight()
{
return height;
}
public int getWidth()
{
return width;
}
public List<E> getElements()
{
return elements;
}
public Iterator<E> iterator()
{
return getElements().iterator();
}
public E get(int x, int y)
{
return getElements().get(
idx(x,y));
}
public E get(int idx)
{
return getElements().get(idx);
}
public void put(int x, int y, E element)
{
put(idx(x,y), element);
}
public void put(int idx, E element)
{
getElements().add(idx, element);
}
public int x(int idx)
{
return idx % getHeight();
}
public int y(int idx)
{
return (idx - idx % getHeight()) / getHeight();
}
public int idx(int x, int y)
{
return y*getHeight() + x;
}
}
以下是如何使用该类(请参见测试示例):
public class TestGrid
{
public static final int SIZE = 10;
public static final Integer el1 = new Integer(2);
public static final Integer el2 = new Integer(3);
public static final Integer el3 = new Integer(3);
public static void main(String[] args)
{
Grid<Integer> grid = new Grid<>(SIZE);
assert grid.getCapacity() == SIZE*SIZE ;
assert grid.idx(0,0) == 0 ;
assert grid.idx(1,0) == 1 ;
assert grid.idx(0,1) == 10;
assert grid.idx(6,1) == 16;
assert grid.idx(9,9) == 99;
grid.put(1, el1);
assert grid.get(1) == el1 : grid.get(1);
grid.put(0, 1, el2);
assert grid.get(0,1) != el1 && el1 != el2 && grid.get(0,1) == el2;
grid.put(15, el3);
assert grid.get(5,1) == el3;
}
}