You will often find the same problem: how to manipulate a 2D array as a 1D array. I wrote a generic Grid class that allows you to access objects using index or (x, y) .
See the following class and understand its idea. :)
You can use the following class to process data as a 2D array or 1D array. Here is the code that I wrote and use.
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; } }
Here's how to use the class (see test case):
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; } }
Willmore
source share