1

I have a problem in understanding how to readout a array that I put into the hash map. (By the way I need to put in different data types into the hash map, single values and also arrays, thatsway I use the generic "Object" type).

Example Code:

HashMap map = new HashMap();

map.put("two", new int[]{1,2});

int[] myArray = new int[2]:

myArray = (int[])map.get("two");

System.out.println("Array value "+myArray[0]);

System.out.println("Array value "+myArray[1]);

I get an error during runtime...

I hope somebody can give me a hint. I can't find my mistake.

Thanks a lot. Steffen

2
  • As an aside you might want to use an ArrayList as opposed to an []. You can use Generics etc then. Commented Dec 13, 2010 at 12:09
  • The line int[] myArray = new int[2]; is unnecessary. You are re-assigning the myArray variable using myArray = (int[])map.get("two");. Commented Dec 13, 2010 at 12:46

2 Answers 2

1

Problem is within this line:

int[] myArray = new int[2]:

change it to

int[] myArray = new int[2];

Other then that there are no problems with the snippet.

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

Comments

0

That code should work fine, with the exception of this line:

int[] myArray = new int[2]:

which uses a colon instead of a semi-colon, and pointlessly creates a new array. Given that you say you get an error at runtime, I suspect this isn't the problem - but it's hard to say, given that you haven't said what the error actually is.

I'd also suggest using generics rather than the raw type, even if the value type is just Object. Here's a short but complete program showing it working:

import java.util.*;

public class Test {
  public static void main(String[] args) {
    Map<String, Object> map = new HashMap<String, Object>();
    map.put("two", new int[] { 1, 2 });
    int[] myArray = (int[]) map.get("two");
    System.out.println("Array value " + myArray[0]);
    System.out.println("Array value " + myArray[1]);
  }
}

Output:

Array value 1
Array value 2

Given that that code works, please post a short but complete program which fails - or at least tell us what error you're actually getting.

2 Comments

@org.life.java: Yes... I suspect the code that was posted isn't exactly the code that was failing.
Dear all, you are correct. The code is working. Unfortunately I was to fast posting my question. The bug is somwhere else, I need to investigate. Thank you, and sorry again. Steffen

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.