Java – Return either a single or two dimensional array

Solution for Java – Return either a single or two dimensional array
is Given Below:

Either create a 1-D array or 2-D array based on the integer value passed. The task can be implemented as shown with the code below but uses Object type to store and return either types. This seems to be a poor coding practice especially because a cast is required every time a value needed to be accessed from the array. I hope there is a cleaner approach to this.

The last request is that the getArray method doesn’t perform any checking and returns the variable itself (i.e., return info;) and instanceof (if used) will be used only once, not every time a value needs to be accessed.

public class MultiArrayType {
    private Object info;//can be either a 1-D or 2-D array

    public MultiArrayType(int x) {
        if (x > 10) {
            info = new long[x][x];
        } else {
            info = new long[x];

    public Object getArray() {
        return info;

    public static void main(String[] args) {
        MultiArrayType t = new MultiArrayType(7);
        Object array = t.getArray();

        if (array instanceof long[]) {
            System.out.println("1D array");
            System.out.println("Index zero is: " + ((long[]) array)[0]);
        } else if (array instanceof long[][]) {
            System.out.println("2D array");
            System.out.println("Cell (0, 0) is: " + ((long[][]) array)[0][0]);
        } else {
            //for safety only :)
            System.out.println("Some other unknown object");