【问题标题】:how to convert a C hashmap to Java如何将 C hashmap 转换为 Java
【发布时间】:2014-10-21 21:37:07
【问题描述】:

我在 C 中有一个很长的结构,看起来像..

something c = 
{
    {123, {1,2,3,4,5,5}},
    {333, {1,2,4}},
    {13}, {6,3,1,2,3,4,5,6,7,7,8}}
    // continue for 100 lines
};

我在 Java 中需要这个,我不知道任何 C 语言,但这看起来像一个哈希图,其中键是整数,值是整数数组。我尝试了类似的东西

HashMap<Integer, Integer[]> something =
{
    123:{1,2,3,4,5,5},
    333:{1,2,4},
    //continue for 100 lines
}

这没有用。

编辑: 所以第一个数字是一个叫做 startX 的 int,而这个数组是满的叫做 startY 的短整数。代码做了类似

int tab = c[num];
int a = tab>startX;
short b = tab>startY;

所以在Java中我相信这就像

int a = something.get(startX);
int b = a[0];

我需要能够遍历数据结构,并希望我不必手动输入所有这些行:/

【问题讨论】:

  • C 没有任何称为“hashmap”的东西,也没有任何类似的数据结构。您正在查看的可能是一组结构,但除非您说出 something 是什么,否则无法分辨。
  • 原来第一个数字只是一个int,而另一个数组很短
  • 所有三个当前答案仍然适用,只需将 Integer[] 更改为 Short[] 或 short[] 如果您愿意。事实上,您甚至不必使用 Integer[],如果它们是 int,只需 int[] 就可以了。自动装箱负责其余的工作。
  • int a = something.get(startX);在检索数组时必须是 int[] a = ...。
  • 在 Java 中,通常最好使用List&lt;Integer&gt; 而不是Integer[],您可以使用其中任何一个作为Map 的值。

标签: java c


【解决方案1】:

试试

HashMap<Integer, Integer[]> something = new HashMap<Integer, Integer[]>();
something.put(123, new Integer[]{1,2,3,4,5,5});
something.put(333, new Integer[]{1,2,4});
//continue for 100 lines

你得到整数数组

Integer[] array = something.get(123);

如果您使用的是 Java 1.7 或更高版本,则可以省略 HashMap 实例化中的类型。

HashMap<Integer, Integer[]> something = new HashMap<>();

【讨论】:

    【解决方案2】:

    您必须手动将它们放入HashMap

    Map<Integer, Integer[]> something = new Map<Integer, Integer[]>();
    something.put(123, new Integer[]{1,2,3,4,5,5});
    something.put(333, new Integer[]{1,2,4});
    //etc
    // Get each array by using something.get() with one of the Integer keys
    something.get(123);
    

    【讨论】:

      【解决方案3】:
      HashMap<Integer, Integer[]> something = new HashMap<Integer, Integer[]>() {
          {put(123, new Integer[]{1,2,3,4,5,5});}
          {put(333, new Integer[]{1,2,4});}
      };
      

      【讨论】:

      • 老实说,我以前从未在 Java 中看到过这种结构。但它有效。
      • @A.Grandt 称为双括号初始化:stackoverflow.com/q/1958636/1530508
      • @ValekHalfHeart 谢谢。
      猜你喜欢
      • 1970-01-01
      • 2011-07-25
      • 2014-09-27
      • 1970-01-01
      • 2015-01-14
      • 1970-01-01
      • 1970-01-01
      • 2010-11-08
      • 2015-06-16
      相关资源
      最近更新 更多