1

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.

4
  • intArray[x] = 4 for example. Commented Jul 31, 2017 at 12:31
  • Are you out of scope of intArray? Why do you need to get it back from the map? Commented Jul 31, 2017 at 12:32
  • @cricket_007 yes, i can't set any positions at intArray on initialization Commented Jul 31, 2017 at 12:48
  • Future note: when you say "anything I try give me an error", actually show those things Commented Jul 31, 2017 at 13:36

2 Answers 2

3

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!

Sign up to request clarification or add additional context in comments.

2 Comments

Thanks, just a quick follow up question, I don't need to "put it back" into the HashMap after inserting the new value, this will be handled automatic?
That is the point of my last paragraph: you have to understand what a reference is. In other words: a reference only points to an object. When you update the "pointed at object" you are good. So yes, it is enough to get() that array - any updates "go" to that one array.
2

You first have to get() the array:

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

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

2 Comments

You do not need to put it back. get gets you a live reference to the object (the array).
Hint: be careful about giving advise to others then. If you are not 98% sure about the content you are talking about - either dont talk about that, or make it clear in your posting where you are *speculating" yourself.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.