Hello, is it possible to have a multidimensional array of different type? We have to create a simple "joke" application with GUI, and what I was thinking is that for each question a character(image) with a speech bubble asks a question like for example a joke about a banana would have a banana (image) asking a question and of course theres a text field for users to answer. so i thought maybe putting the image and question together into an array or something so then we could just call that array out later. I dont know, we maybe be making things difficult for ourselves with this approach but that's all we came up with. because as an example our lecturer used knock knock jokes so it had a background of a door with a speech bubble that would display the joke and a constant character (image) with a text box next to it for user to insert an answer. so that sort of gave the idea but instead of a constant image character, it changes according to the question. So yeah, unless theres a different approach to this?

Recommended Answers

All 2 Replies

Not in Java. You can use ArrayList<MyObject> and make MyObject flexible enough to cope with more than one type.

In other more-flexible languages you can be more direct. In Ruby, for example:

stuff = ["a", :a, 1, ["a", :a], {a: 1}]
=> ["a", :a, 1, ["a", :a], {:a=>1}]

Not in Java

??? Object[][[] is a multi-dimensional array that holds anything.

Because every object extends Object, and primitives are auto boxed/unboxed into the corresponding objects as required, then you can put anything into a multi-dimensional array of Object (including other arrays).
Having said that, it's a terrible idea. You bypass all Java's type checking, so code errors will be hard to find, and before you use any of those Objects you will have to do an unsafe runtime cast to String, Image or whatever. And the code will be really hard to follow.

Let's try thinking in Object Orientation instead (after all, this is Java)...

Why not create a Joke class, with text, image etc as instance variables, and then it's a simple array of Jokes. All the variables are strongly typed, so fewer errors, and extending the app with more info about a Joke is trivial. Plus, the code will bo so much easier to read and understand.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.