简体   繁体   中英

Different variable types in the SAME ARRAY? (Java)

The program I am creating a program in which a method is using A LOT of different 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. Eg

  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.

您可以使用Object [] [],因为String是对象。

为什么不使用一个Object并将所有数组放入其中。

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM