创建一个在Java中存储字符串和整数的数组 [英] Creating an array that stores strings and integers in java
问题描述
我想创建一个存储公司股票名称(字符串)和值(整数)的数组,但是我不知道该怎么做.
I would like to create an array that stores the names (String) and values (integer) of company stocks, but I don't know how to go about it.
推荐答案
Object []
可以容纳 String
和 Integer
对象.这是一个简单的示例:
An Object[]
can hold both String
and Integer
objects. Here's a simple example:
Object[] mixed = new Object[2];
mixed[0] = "Hi Mum";
mixed[1] = Integer.valueOf(42);
...
String message = (String) mixed[0];
Integer answer = (Integer) mixed[1];
但是,如果您像这样使用 Object []
放置,则通常需要在访问元素时使用 instanceof
和/或键入强制类型转换.
However, if you put use an Object[]
like this, you will typically need to use instanceof
and / or type casts when accessing the elements.
任何通常涉及 instanceof
和/或类型强制转换的设计都应引起怀疑.在大多数情况下,有一种更好的方法(更面向对象,更高效,更不易碎)来达到相同的目的.
Any design that routinely involves instanceof
and/or type casts needs to be treated with suspicion. In most cases, there is a better (more object-oriented, more efficient, less fragile) way of achieving the same ends.
在您的特定用例中,听起来您真正需要的是一个映射对象,该对象从 String
(名称)映射到 Integer
(股票数量).关于Java的好处是,已有的库类提供了此功能.例如 HashMap< K,V>
类,其中 String
是键类型,而 Integer
是值类型.
In your particular use-case, it sounds like what you really need is a mapping object that maps from String
(names) to Integer
(numbers of stocks). And the nice thing about Java is that there are existing library classes that provide this functionality; e.g. the HashMap<K,V>
class, with String
as the key type and Integer
as the value type.
另一种可能是一些自定义或通用对类的数组, List
或 Set
.这些对 Map
类型具有不同的语义属性.
Another possibility might be an array, List
or Set
of some custom or generic pair class. These have different semantic properties to Map
types.
这篇关于创建一个在Java中存储字符串和整数的数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!