Array2D { @SuppressWarnings("unchecked") public void setDimensions(int width, int height) { List<T> newArr = new ArrayList<>(width * height); List<T> subArr; int oldWidth = this.width; int oldHeight = this.height; int x; int y; this.width = width; this.height = height; for (y = 0; y < oldHeight; y++) { subArr = arr.subList(y * oldWidth, (y + 1) * oldWidth); newArr.addAll(y * width, subArr); for (x = oldWidth; x < width; x++) { if (arr.get(0) instanceof Tile) { newArr.add(y * width + x, (T) new Tile(x, y, 0)); } else if (arr.get(0) instanceof Integer) { newArr.add(y * width + x, (T) new Integer(0)); } } } for (y = oldHeight; y < height; y++) { for (x = 0; x < width; x++) { if (arr.get(0) instanceof Tile) { newArr.add(y * width + x, (T) new Tile(x, y, 0)); } else if (arr.get(0) instanceof Integer) { newArr.add(y * width + x, (T) new Integer(0)); } } } this.arr = newArr; } Array2D(int width, int height); void initialise(int x, int y, T val); T get(int x, int y); void set(int x, int y, T val); int getWidth(); int getHeight(); @SuppressWarnings("unchecked") void setDimensions(int width, int height);  }
@Test public void testSetDimensions() { arr.setDimensions(40, 40); assertEquals((Integer) 1417, arr.get(17, 14)); assertEquals((Integer) 0, arr.get(34, 36)); arr.set(39, 39, new Integer(3939)); assertEquals((Integer) 3939, arr.get(39, 39)); arr.setDimensions(20, 20); assertEquals((Integer) 1417, arr.get(17, 14)); }