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.
-
Any tries by yourself? – drgPP Dec 10 '14 at 13:58
-
Create a class to hold these attributes and then create an array to hold instances of this class. – Alexis C. Dec 10 '14 at 13:59
-
If the name is the key then use an map like Map
myMap = HashMap – Rene M. Dec 10 '14 at 14:01(); Or if you realy need an array you can use an object which holds the variables. -
Or use a Map
– Lucas Dec 10 '14 at 14:01 -
You have a typo: interger is supposed to be integer. Please fix it – mohsaied Dec 10 '14 at 14:08
-
@Billy you mis-spelled **integer** (it's not called inte**r**ger). Why did you roll-back the fix to your spelling error? – Erwin Bolwidt Dec 10 '14 at 14:54
-
@Erwin. it was an oversight on my part. Thank you for pointing it out – Billy Dec 11 '14 at 09:29
3 Answers
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];
However, if you put use an Object[]
like this, you will typically need to use instanceof
and / or type casts when accessing the elements.
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.
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.
Another possibility might be an array, List
or Set
of some custom or generic pair class. These have different semantic properties to Map
types.

- 698,415
- 94
- 811
- 1,216
You have two choices:
- Use an array.
public class Value { public String name; public int number; } ... public Value[] values = new Value[10]; ....
- Use a map which has much more comfort, specially you can use the name as key to get a value
.... public Map<String, int> valueMap = new HashMap<String,int>(); valueMap.put("Sample",10); int value = valueMap.get("Sample"); ...

- 2,660
- 15
- 24
You can use a Map data structure instead of an array. This is basically a type of Collection that has key-value pairs. Your string name can be used as the key and the value is your integer.
Map<String,Integer> myMap = new HashMap<String, Integer>;
MyMap.put("someone", 6);
Note that using a HashMap has a speed advantage over an array during lookup. The complexity of HashMap lookup is O(log(n)) while that of an array is O(n).

- 2,066
- 1
- 14
- 25
-
Thank you for the answer. The question i have specifically asks for an array. – Billy Dec 10 '14 at 14:40