开发者

How to readout Array from hash map?

开发者 https://www.devze.com 2023-01-30 20:51 出处:网络
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 us

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


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.


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.

0

精彩评论

暂无评论...
验证码 换一张
取 消