简体   繁体   English

SAME ARRAY中的变量类型不同? (Java)

[英]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? 我的问题是如何将String[]数组与Object[]数组组合?

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. 具有所有公共字段(如果您的数据应该是不可变的,请添加final )或具有getter和setter的JavaBean的记录类型数据结构。 Lots of arrays of primitives values is very procedural, Java is an Object orientated language so use this in your design. 许多原始值数组都是非常程序化的,Java是一种面向对象的语言,因此请在设计中使用它。

To add to @styfle's comment; 在@styfle的评论中添加; 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. 现在可以存储任何对象,字符串,日期,JButton等。但是,当您从数组中检索项目时,这可能很危险。 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. 一种选择是使用ArrayList<Superclass[]> ,其中超类是您正在使用的所有内容都继承自的某个类。 If there is no such class, then use Object. 如果没有此类,请使用Object。

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

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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