Java Generic Primitive type nd array

I need to pass a primitive 2d array to the filtering procedure. The filtering algorithm (median filter) is the same regardless of the type of array. Is there a way to pass any type of array in a general way or should I overload the same function with different types of arrays. In the second case, the same code will have to be repeated for different data types.

int[][] medianfilter(int[][] arr){ ... }
float[][] medianfilter(float[][] arr){ ... }

Is there a way to make the above code generic instead of repeating the code for the media filter in each of each overloaded function?

+3
source share
3 answers

Object. .

( ), DoubleAlgorithm , double getElement(int i, int j) handleResult(double result), .

(, ).

public int filter(int [][] values) {
   IntAlgorithm algo = new IntAlgorithm(values);
   algo.run();
   return algo.getResult();
}
public double filter(double [][] values) {
   DoubleAlgorithm algo = new DoubleAlgorithm(values);
   algo.run();
   return algo.getResult();
}

public class AbstractAlgorithm {
  public  run() {
     double sum = 0.0;
     for(int i=0; i<rows(); i++) {
       for(int j=0; j<columns(i); j++) {
          sum+=getElement(i, j);
       }
     }
     handleResult(sum);
  }
  protected abstract int rows();
  protected abstract int columns(int row);
  protected abstract double getElement(int i, int j);
  protected abstract void handleResult();
}

public class IntAlgorithm extends AbstractAlgorithm {
    int [][] values;
    int result;
    IntAlgorithm(int [][] values) {
       this.values= values;
    }
    public int rows() {
      return values.length;
    }
    public int columns(int row) {
      return values[row].length;
    }
    public double getElement(int i, int j) {
      return values[i][j];
    }
    public void handleResult(double result) {
      this.result = (int)result;
    }
    public int getResult() {
      return result;
    }
}

, , , . , , .

, , ints/longs , . , , , (, ) . , , .

+1

, ( java.util.Arrays) .

Object[] medianfilter(Object[] arr); // note the missing dimension

, . , System.arraycopy. . .

int[][]  result = (int[][]) medianFilter( input );

.

+1

:

public T test(T[][] arg)
{
    T[][] q = arg;
    T[]   r = q[0];
    T     s = r[0];

    return s;
}

... unfortunately, this will not work for primitive types. You will need to use Integer and Float as your parameterized types.

+1
source

Source: https://habr.com/ru/post/1765953/


All Articles