1

For my project, I need a 2D array that can hold multiple different object types. The problem with java is that it doesn't let you do that. You can only have an array of a particular object type.

Now don't get me wrong, but I did some research, and one proposed solution is to use an Object array, since every class in java extends the object class by default. For example:

Object[][] someArray = new Object[5][5];
someArray[1][2] = new Cat();
someArray[3][4] = new Dog();

The problem with this is that the object class, being a superclass, cannot access the methods and fields of the subclasses that extend it. So if I have a public eat() method in my cat or dog class, the elements in someArray wont be able to access that method.

So I'm at a dead-end here. Any help is appreciated. Thanks in advance.

4
  • everything in java is an object!!! Commented Jun 14, 2017 at 3:57
  • if object is not a solutionthen use inheritance and interfaces.... Commented Jun 14, 2017 at 3:58
  • Use instanceof and casting to check the type of a given Object and and to convert it to that type accordingly. Commented Jun 14, 2017 at 4:00
  • Why do you want a 2D array filled with different objects? You will need to cast to get to their specific methods. Maybe you should look for a common interface besides Object. Commented Jun 14, 2017 at 5:58

4 Answers 4

1

[ please don't judge me for answering my own question ]

One possible solution is using 2D ArrayLists. The way a 2D Array works is by literally having a 1D array consisting of 1D arrays.

Maybe the same concept can be applied to ArrayLists, which can in fact store any object types without having accessibility issues. A 5x5 ArrayList can be created as follows:

ArrayList<ArrayList> someArray = new ArrayList<ArrayList>();
for(int x=0 ; x<5 ; x++)
{
    someArray.add(new ArrayList());
    for(int y=0 ; y<5 ; y++)
        someArray.get(x).add(null);
}

and to set row 1 col 2 to a cat object:

someArray.get(1).set(2, new Cat());
someArray.get(3).set(4, new Dog());

So 2D ArrayLists, though a bit confusing might solve this issue pretty efficiently.

Sign up to request clarification or add additional context in comments.

2 Comments

You're not being judged. in fact, it is encouraged to answer your question if you find out what the problem is. I'm glad you figured it out. +1 :)
While it is better to use List this doesn't really solve your problem.
1

to call the eat() method of the Dog class and `Cat`` class, You can cast the array reference to a subclass reference.((Dog)someArray[x][y]).eat();

public class Dog{

    public Dog(){
        super();
    }

    public String eat(){
      String str = "yum";
      return str;
    }

    public static void main (String[]args){
        Object [][] arr = new Object [2] [2];
        for(int i = 0; i < arr.length; i++){
            for(int j = 0; j < arr[i].length; j++){

               arr[i][j] = new Dog(); 
            }
        }
       System.out.println(((Dog)arr[1][1]).eat());
    }
}

1 Comment

ClassCastException is thrown. You can't cast superclass object to its subclass.
0

The ideal use in your case is to create a superclass called Animal that is extended by dog and cat. Your ArrayList or array will be of Animal type.

Comments

-1

How different do these objects need to be? If they're your own classes, then just create some sort of superclass that they all extend and use that as the array type. If you don't want to do that, I guess you could set something up like this:

private Object[][] array = new Object[5][5];

public void setValue(int x, int y, Object val) {
    if(x > 0 && x < array.length && y > 0 && y < array[0].length) {
        array[x][y] = val;
    }
}

public Object getValue(int x, int y) {
    if(x > 0 && x < array.length && y > 0 && y < array[0].length) {
        return array[x][y];
    }
    return null;
}

Using it would be a little tedious, but you could cast each call to getValue() to the type you needed it to be. With Object Oriented programming, having a simple solution to this can be kind of difficult. I could write some more advanced code that would return the object casted to a certain class, but it's a little bit of work. Let me know if you'd like that.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.