0

Good time of the day to anybody reading,

I would like to ask if the following situation is possible to do in Java:

What do I want to do - create a 2D array which can have different objects in it (i.e. in [0][2] I would like to have PreRoom object, in [0][3] - Room object) and would like these object to be accessible (obviously).

How am I doing this?

1) Declare 2D array of Object type:

Object[][] map = new Object[151][151];

2) Create an object:

map[0][2] = new PreRoom(r, true);

3) But after this I'm unable to use any method of PreRoom/get any its property, i.e. unable to do:

map[0][2].x;
//or
map[0][2].getR;

Am I doing this wrong? Or it's impossible to do and therefore the only solution is to create a unified object for current 2?

Thanks in advance.

EDIT: solution found, thanks for the replies.

Denis Korekov
  • 203
  • 1
  • 2
  • 10
  • 1
    Either explicitly cast it, or if you can't rely on the type of the object, then an [instanceof](http://stackoverflow.com/questions/7313559/what-is-the-instanceof-operator-used-for) check may be of benefit to you. – Dan Temple Mar 18 '14 at 13:04

3 Answers3

1

You declare Object[][] map = new Object[151][151]; So anything you store in it will be an Object (Obviously), so how does it know that your Object in map[0][2] is of PreRoom? You will need to cast it as such so you can use any methods of PreRoom

((PreRoom)map[0][2]).methodName();

Be careful in future if you are storing numerous types in your map. You may find instanceof useful if you ever need to iterate through your map not knowing which values are of what.

For example;

if(map[x][y] instanceof PreRoom) {
   //map[x][y] is an instance of your PreRoom class
   PreRoom preRoomObj = (PreRoom) map[x][y];
}
Stu Whyte
  • 758
  • 5
  • 19
1

You can define an interface or abstract class that will be implemented/inheritedd by both PreRoom and Room class.

Then you array could be something like

<InterfaceName/AbstractClassName>[] = new <InterfaceName/AbstractClassName>[151][151];

You interface or base class should declare the common methods and variable.

sheu
  • 284
  • 5
  • 13
  • While I realize this doesn't technically answer the question, this is what you should do if you want to keep your code maintainable and well structured. – Mikkel Løkke Mar 18 '14 at 13:12
0

Here you need to explicitly type cast to call the methods on that object

((PreRoom)map[0][2]).x  
RKC
  • 1,834
  • 13
  • 13