猿问

使用 Java 中的基本类型创建具有内部矩阵表示的 Matrix 泛型类

我有一个 Matrix 类,旨在封装数组的原始数组。我需要使用通用版本而不在内部使用对象来解决内存分配问题。有没有办法在Java中做到这一点?我可以做一系列 if 语句来检查类型,但可能有更好的方法来做到这一点。


一只斗牛犬
浏览 266回答 3
3回答

繁花如伊

您始终可以将数组包装在一个实现的对象中List<List<Integer>>,然后将其视为矩阵。private static class Matrix extends AbstractList<List<Integer>> implements List<List<Integer>> {&nbsp; &nbsp; final int[][] data;&nbsp; &nbsp; private static class Row extends AbstractList<Integer> implements List<Integer> {&nbsp; &nbsp; &nbsp; &nbsp; final int[] row;&nbsp; &nbsp; &nbsp; &nbsp; public Row(int[] row) {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; this.row = row;&nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; &nbsp; &nbsp; @Override&nbsp; &nbsp; &nbsp; &nbsp; public Integer get(int index) {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; return row[index];&nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; &nbsp; &nbsp; @Override&nbsp; &nbsp; &nbsp; &nbsp; public int size() {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; return row.length;&nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; }&nbsp; &nbsp; public Matrix(int[][] data) {&nbsp; &nbsp; &nbsp; &nbsp; this.data = data;&nbsp; &nbsp; }&nbsp; &nbsp; @Override&nbsp; &nbsp; public List<Integer> get(int index) {&nbsp; &nbsp; &nbsp; &nbsp; return new Row(data[index]);&nbsp; &nbsp; }&nbsp; &nbsp; @Override&nbsp; &nbsp; public int size() {&nbsp; &nbsp; &nbsp; &nbsp; return data.length;&nbsp; &nbsp; }}public List<List<Integer>> asMatrix(int[][] data) {&nbsp; &nbsp; return new Matrix(data);}private void test() {&nbsp; &nbsp; int[][] test = new int[][] {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; {1,2,3},&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; {4,5,6},&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; {7,8,9}&nbsp; &nbsp; };&nbsp; &nbsp; List<List<Integer>> matrix = asMatrix(test);&nbsp; &nbsp; System.out.println(matrix);}这种方法可以扩展为允许仅通过set在内部Row类中实现来写回内部数组。扩展Matrix以允许get(row,col)方法将是微不足道的。您需要为需要处理的每个原语编写其中之一。

ABOUTYOU

为了速度和紧凑性,我们中的许多人在原始类数组的顶部添加了一个矩阵访问器垫片。例如(伪代码)&nbsp; int data[WIDTH*HEIGHT]; // populate it&nbsp; int at(int x, int y) { return data[y*WIDTH+x]; }
随时随地看视频慕课网APP

相关分类

Java
我要回答