Search code examples
javaarraysgenericsmultidimensional-arraystatic-array

Java: Generic Static Multidimensional Arrays


If it is possible, how can I create a static multidimensional array in Java with different primitive datatypes per dimension?

By static, I mean the primitive array that is not dynamic like an ArrayList would be.


Solution

  • Dimensions in an Array are always from type int. Think about it!

    int a = 4;
    int b = 5;
    
    Shoe shoe = new Shoe (Color.RED, 42, "Leather");
    Hat hat = new Hat (17, Color.Black);
    
    Foo foo = foos[a][b];
    Zilch pop = bars[shoe][hat]; // no go
    

    If you have a multidimensional array of Foos, the first dimension is an Foo, the second an array of Foos, the third an array of array of Foo. The only variable type is the one at the bottom.

    Edit after update of question:

    Arrays aren't called static or primitive. Their size is fixed on initialization, and what they have in common with primitives is, that they are a buildin, which is threated special in some cases. They are - in contrast to the so called primitive types, which aren't that primitive (they have, for example, operators, exclusively for their own, like * / -) but meanwhile they are objects, but not declared in the library.

    Call them build in-types.

    Using Bhesh Gurung's trick:

    Object[] arr = {new Integer[]{}, new String[]{}, new Double[]{}}; 
    

    is begging for trouble, and it is not made of different datatypes per dimension. Let's start with the dimensions:

    // One-dimensional object:
    JPanel [] panels = new JPanel [3]; 
    // Two-dimensional object:
    JPanel [][] panels = new JPanel [3][10]; 
    

    You have JPanels on the bottom level, and an Array of JPanel on the next dimension. You can add more dimension, and will always get an additional (Array of ...) wrapped around.

    You can not mix different datatypes in an Array like int and char, or JPanel and JFrame, or int and JButton. Only if you abstract over the difference, and use an JComponent for JPanel and JFrame as common parent, but this will not work for the build-in types int, char, boolean and so on, because they aren't objects.

    But can't you use autoboxing, and use Integer instead of int, Character instead of char, and then use Object as common parent class? Yes, you could, but then you're not using the primitives any more, and you're begging for troubles.

    Dan is talking about a different thing - using differnt types for indexing in the multi-dimensional array:

    byte  b = 120;
    short s = 1000;
    String o [][] = new String[b][s];
    b = 7;
    s = 9;  
    o[b][s] = "foobar";
    String foo = o[b][s];
    

    There is no problem using bytes or shorts, but you can't restrict the size of an Array by declaring it as byte or short. In most cases the boundaries of a build-in integer type will not fit to a datatype (think 365 days per year), especially, since all types might get negative, so bounds-checking is necessary although and can't be restricted to compile time.

    But now to the trouble:
    We could declare the array as two-dimensional from the beginning:

    Object[][] ar2 = {
        new Integer [] {4, 5, 6}, 
        new String [] {"me", "and", "you"}, 
        new Character [] {'x', 'y', 'z'}};
    

    That works fine, and makes the inner arrays accessible immediately without casting. But it is only known for the compiler, that the elements are Object arrays - the underlying type is abstracted away, and so we can write:

    ar2[1][1] = 17; // expected: String
    ar2[2][0] = "double you"; // expected: Char
    

    This will compile flawlessly, but you're shooting yourself in the foot and get a Runtime exception for free.

    Here is the source as a whole:

    public class ArrOfMixedArr
    {
        public static void main (String args[])
        {
            Object[] arr = {
                new Integer [] {1, 2, 3}, 
                new String [] {"you", "and", "me"}, 
                new Character [] {'a', 'b', 'c'}};
            show (arr);
            
            byte b = 7;
            short s = 9;
            String o [][] = new String[200][1000];
            o[b][s] = "foobar";
            String foo = o[b][s];
            
            Object[][] ar2 = {
                new Integer [] {4, 5, 6}, 
                new String [] {"me", "and", "you"}, 
                new Character [] {'x', 'y', 'z'}};
            show (ar2);
    
            // exeptions:
            ar2[1][1] = 17; // expected: String
            ar2[2][0] = "double you"; // expected: Char
        }
    
        public static void show (Object[] arr)
        {
            for (Object o : arr) 
            {
                if (o instanceof Object[])
                    show ((Object[]) o);
                else 
                    System.out.print (o.toString () + "\t");
            }
            System.out.println ();
        }
    }
    

    Now what is the solution? If your base-types arrays of (int, byte, char, String, JPanel, ...) are of equal length, then you have something like a hidden Object, a database-row. Use a class instead:

    class Shoe {
        byte size;
        String manufactor;
        java.math.BigDecimal price;
        java.awt.Color color;
    }
    
    Shoe [] shoes = new Shoe [7];
    

    If you don't have different types of the same size, they might be unrelated, and should not be put in a common container.