简体   繁体   English

如何从哈希图中读出数组?

[英]How to readout Array from hash map?

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. 我也建议使用泛型而不是原始类型,即使值类型只是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. 鉴于该代码有效,请发布简短但完整的程序,该程序将失败-或至少告诉我们您实际遇到的错误。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM