chrillelundmark
chrillelundmark

Reputation: 345

Understanding java hashmap and setting object's value

I am migratimg an old visual basic application to Android and as I progressed I ran into some problems i can't solve. (I'm new to java)

In VB there is something called Dictionary and after googling the equivalent in java I come to the conclusion the thing to use is HashMap.

I need to create a HashMap with a string as key and an int[] as object:

HashMap<String, int[]> hm

So far, so good. I learned that after creating my int[] I set the HashMap the following way...

int[] intArray = new int[23];
hm.put("myRandomString", intarray);

Now to the problem, how can I change the value on position x in my intArray?

I know I will use the key to find the intArray but anything I try give me an error.

Upvotes: 1

Views: 95

Answers (2)

Mads T
Mads T

Reputation: 530

You first have to get() the array:

int[] arrToBeModified = hm.get("myRandomString");

arrToBeModified[0] = 123; // Do your modifications here.

Upvotes: 2

GhostCat
GhostCat

Reputation: 140465

Simple:

String someKey = "myRandomString";
int[] arrayFromMap = hm.get(someKey);
if (arrayFromMap != null) {
  arrayFromMap[x] = y;

Beyond that, you could/should use methods such as:

if (hm.contains(someKey))

or

if (arrayFromMap.length > x)

to check for all the possible things that could go wrong here. Also pay attention to details such as:

int[] oneArray = { 1, 2 , 3};
hm.put("a", oneArray);
hm.put("b", oneArray);

which adds the same array using two different keys. When you know do get("a") and manipulate the corresponding array, the value for "b" changes, too!

Upvotes: 3

Related Questions