【问题标题】:Add value without using index in 2D arrayList inside a HashMap, Java在 HashMap,Java 内的 2D arrayList 中添加值而不使用索引
【发布时间】:2015-09-15 06:16:41
【问题描述】:

无论如何,我对 ArrayLists 还是很陌生,但我需要它们来完成这个模拟项目,如果你们能帮助我,我将不胜感激!

我有一个 2D arrayLists 的 HashMap,在基于 String 键的每次模拟迭代中应该填充“值”和“时间”。我将我的变量定义如下:

protected Map<String, ArrayList<ArrayList<Object>>> history = new HashMap<String,ArrayList<ArrayList<Object>>>();

,我这样初始化它:

for (String act:keySet)  
   history.put(act, new ArrayList<ArrayList<Object>>());

我的 Map 的每个 ArrayList 都有两个 arrayList,在每次迭代中,我应该在每个 arrayList 中添加我的“值”和“时间”,这样我就可以将我的数据及其各自的时间存储在一起,但我不知道当我们可以这样做时,如何使用键,在不使用索引的情况下调用我的数组列表:

tmpData.add("foobar"); // Example

任何帮助将不胜感激。

瓦希德

【问题讨论】:

  • Every ArrayList of my Map has two arrayList 是什么意思?
  • 我的意思是我有两个数组列表的arrayList,一个用于“值”,一个用于“时间”。
  • 你最好改写这个问题,或者添加一个例子来澄清你想要什么,我得到了地图部分,以及将包含两个 ArrayLists 的 ArrayList,但我没有得到的是那些两个数组列表包含。
  • 所以基本上ArrayList&lt;Object&gt; 的大小总是2,这就是你的意思吗?
  • 对不起,伙计们的困惑!我的哈希映射包含字符串键和数组列表,每个数组列表实际上是 2D,应该存储 2 个值,其中是“时间”和相应的“值”,所以我的 HashMap 就像“data1”,{{0,1},{ 1,3},{3,-10},...}。 "data2",{{0,-4},{1,3},{2,12},...}

标签: java arraylist hashmap


【解决方案1】:
protected Map<String, ArrayList<ArrayList<Double>>> history = new HashMap<String,ArrayList<ArrayList<Double>>>();
    Double time=null;
    Double value=null;
    time2=null;
    ArrayList <Double> inner=null;
    for (String act:keySet){
      ArrayList<ArrayList<Double>> outer=null;
      if ((outer=history.get(act))==null)
      {
         outer= new ArrayList<ArrayList<Double>> ();
      }
       inner=new ArrayList <Double>();
       time= value1;//your value for this integer 
       value= value2;
       inner.add(time);
       inner.add(value);
       outer.add(inner);

       history.put(act, outer);
       }

在每次迭代中,我们检查映射是否包含该键,如果是,我们添加一个新的,我们用新的时间对象填充内部 ArrayList,并将其添加到预先存在的外部 ArrayList,然后我们更新外部的值ArrayList与那个key关联,如果不包含那个key我们创建outer map,inner map,时间对象填充inner ArrayList,outer ArrayList,把outer ArrayList和key关联起来。

【讨论】:

  • 感谢您的回答。
  • 这个答案是根据我的理解,我不确定它是否符合您的要求,是吗?
  • 我在使用此代码时出错。这里的时间课是什么?实际上是前面定义的time1吗?
  • 哦,我以为您的内部 ArrayList 包含您创建的时间类对象。
  • 不,我的内部数组列表包含我的“时间”和“值”作为要存储的双数。在这种情况下,你能帮我吗?
猜你喜欢
  • 2017-01-16
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-02-22
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2014-03-01
相关资源
最近更新 更多