Billy
Billy

Reputation: 11

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.

Upvotes: 0

Views: 24054

Answers (3)

mohsaied
mohsaied

Reputation: 2126

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).

Upvotes: 0

Stephen C
Stephen C

Reputation: 718788

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.

Upvotes: 2

Rene M.
Rene M.

Reputation: 2690

You have two choices:

  1. Use an array.
public class Value {
  public String name;
  public int number;
}

...
public Value[] values = new Value[10];
....
  1. 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");
...

Upvotes: 1

Related Questions