Different variable types in the SAME ARRAY? (Java)
The program I am creating a program in which a method is using A LOT of di开发者_JAVA百科fferent arrays! For me, it is rather difficult to keep track of all them. So, why not combine them into a multi-dimensional array? My problem is how can I combine a String[]
array with a Object[]
array?
Can someone help me with this?
This sounds like your missing an abstraction, if all your arrays are the same length there is probably a class that you should be defining; a record type data structure that either has all public fields (if your data should be immutable add final) or a JavaBean with getters and setters. Lots of arrays of primitives values is very procedural, Java is an Object orientated language so use this in your design.
To add to @styfle's comment; if they're unrelated why would you want to do this? And if they're related why aren't you defining classes?
If you declare an array of a particular type, all subtypes can be stored in the array. E.g.
Object myArray[];
can now store any object, Strings, Dates, JButtons etc. However, this can be dangerous when you are retrieving the items from the array. You have to ensure that you interpret them correctly. The compiler would not be able to warn you if you store the wrong type of object in there.
A better approach might be to create your own collection object that stores all the various items in a way that is type safe.
One option would be to use an ArrayList<Superclass[]>
where superclass is some class from which everything you're using inherits. If there is no such class, then use Object.
You can use Object[ ][ ], as String are objects.
Why not using one Object
and put all your arrays in it.
精彩评论