Search code examples
javamemory-managementgeneric-programmingprimitive-types

Create a Matrix generic class with internal matrix representation using primitive types in Java


I've a Matrix class that aim to encapsulate a primitive array of array. I need to use a generic version without using objects internally for memory allocation problems. Is there any way to do that in Java? I can make a series of if statements to check the type but probably there is a better way to do it.


Solution

  • You can always wrap the array in an object that implements List<List<Integer>> and then treat that as a matrix.

    private static class Matrix extends AbstractList<List<Integer>> implements List<List<Integer>> {
        final int[][] data;
    
        private static class Row extends AbstractList<Integer> implements List<Integer> {
            final int[] row;
    
            public Row(int[] row) {
                this.row = row;
            }
    
            @Override
            public Integer get(int index) {
                return row[index];
            }
    
            @Override
            public int size() {
                return row.length;
            }
        }
    
        public Matrix(int[][] data) {
            this.data = data;
        }
    
        @Override
        public List<Integer> get(int index) {
            return new Row(data[index]);
        }
    
        @Override
        public int size() {
            return data.length;
        }
    }
    
    public List<List<Integer>> asMatrix(int[][] data) {
        return new Matrix(data);
    }
    
    private void test() {
        int[][] test = new int[][] {
                {1,2,3},
                {4,5,6},
                {7,8,9}
        };
        List<List<Integer>> matrix = asMatrix(test);
        System.out.println(matrix);
    }
    

    This approach can be extended to allow writing back to the inner array just by implementing set in the inner Row class. Extending Matrix to allow a get(row,col) method would be trivial.

    You will need to write one of these for each primitive you need to handle.