Home > other >  Process multi dimensional arrays in Java
Process multi dimensional arrays in Java

Time:08-09

What is the best way to take in a multi dimensional array as a method parameter in the form of an object and then reconstruct it as a variable inside that method? The reason I want to pass the array in as an object is because I want my code to be able to use any n dimensional array. I could circumvent this by using method overloading but making hundreds of identical methods just to account for all possible array dimensions seems like a very bad way to do it. However, using an object as a parameter causes a new set of challenges since I have no way to initialize that array since you normally need to explicitly declare an arrays dimensions. Based on some of my research I have figured out a way to determine the dimensions of an array passed in as an object which you can view in the following code snippet.

 public static void callTestArray() {
    var matrix = new int[][]{{1,2}, {4, 6, 7}};
    test(matrix);
}

public static void test(Object obj) {
    final int dimensions = dimensionOf(obj);
    System.out.println("Dimensions:"   dimensions);
    
    //I can't create a variable from this though since I need to hard code the dimensions of the array
}

/**
 * This returns the amount of dimensions an array has.
 */
public static int dimensionOf(Object arr) {
    int dimensionCount = 0;
    Class<?> c = arr.getClass(); // getting the runtime class of an object

    while (c.isArray()) { // check whether the object is an array
        c = c.getComponentType(); // returns the class denoting the component type of the array
        dimensionCount  ;
    }
    return dimensionCount;
}

I have been looking around for a while now but I cant find an object that allows me to pass in any n dimensional array in that allows me to easily access all of an arrays typical information? Was this not included in Java or am I just missing it? That being said since 255 is the max amount of dimensions an array can have I could make my own utils class to handle this but it would require a ton of redundancies and effort to handle all cases. I just want to make sure it has not already been made before I waste hours making something like that. Also if anyone has a better way of doing it with any internal java libraries please let me know!

CodePudding user response:

Instead of passing around arrays we more often than not use collections like ArrayList, this allows us some abstraction and allows us to add some common methods to it. Note that ArrayList doesn't extend arrays, it simply implements a list interface.

I recommend the same thing for you, instead of passing around an array, consider encapsulating the array in a class and pass that class around. Use the class to do certain simplifications, for instance you might have a method allowing it to apply a function to each element of the matrix or one to resize the matrix.

You might track your matrix's dimensions in different variables allowing you to resize it without re-allocating the array (like an ArrayList does)

Another advantage of the encapsulation, if you wish to do something different like make a sparse matrix out of it, you could re-implement the underlying code without changing the ways it's used (Like the way ArrayList and LinkedList have the same interface but do things different ways for different use cases)

Your other conditions seem to work for this Matrix object as well as it would arrays, for instance you would pass dimensions into the constructor to create it initially (Although, as I said, you could easily expand it later, especially if you used an ArrayList of ArrayLists for your underlying implementation, if you needed that)

I think the reason it's not included in Java is that it is not very commonly used and quite easy to implement, but if you really don't want to do it yourself, apache has a Matrix implementaiton that looks like it will fit.

We use time series data like hourly tempatures a lot (Often down to 10 second resolution for a day) and so we built our own class that essentially represents a line on a graph with the y access of "Date", like a linked list but each value is timestamped. This structure is AMAZINGLY useful for us and I often wonder why it's not in Java, but I think I just answered my own question, not used enough.

CodePudding user response:

This is a job for varargs:

    public static void main(String[] args) {
        var matrix = new int[][]{{1,2}, {4, 6, 7}};
        System.out.println("Length is: "   getSize(matrix));
    }

    public static int getSize(int[]... multiArray) {
        return multiArray.length;
    }

which prints out:

Length is: 2

Also, unless you have to use an array to hold your int arrays, I would use an ArrayList<int[]> instead. That way you can easily add to your list like:

ArrayList<int[]> multiArray = new ArrayList<>();

multiArray.add(new int[]{1,2,3});
multiArray.add(new int[]{4,5,6});

and then you can get its size by simply calling:

multiArray.size()
  • Related