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.

1
  • 1
    Either explicitly cast it, or if you can't rely on the type of the object, then an instanceof check may be of benefit to you. Commented Mar 18, 2014 at 13:04

3 Answers 3

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];
}
Sign up to request clarification or add additional context in comments.

3 Comments

Not the first to answer, but for anyone else coming here will be definitely the best answer, thanks.
No worries :) If you think it answered your question (or any of the other answers for that matter) please mark one as correct :)
Was unable to do it in first 10 min-s after posting:)
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.

1 Comment

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.
0

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

((PreRoom)map[0][2]).x  

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.