【问题标题】:How to fix a loop through a Hashmap<int<arraylist>> assigning more values than expected如何通过分配比预期更多的值的 Hashmap<int<arraylist>> 修复循环
【发布时间】:2019-01-15 13:07:43
【问题描述】:

提前感谢您的宝贵时间! 我正在研究 Fruchterman Reingold Graph 创建器,但我陷入了一个看似非常简单的问题。长话短说,我想初始化一个 Hashmap,其中包含一个整数键,即我所在的顶点,以及一个整数列表,即 x 位置和 y 位置。然而,下面的代码将每个键放置 8 个而不是 2 个位置值而不是 2 个。非常感谢任何帮助或提示!

package testing.ground;

import java.util.*;


public class TestingGround {


public static void main(String[] args) {


    Random ranx = new Random();
    Random rany = new Random();
    HashMap<Integer,List<Integer>> positions=new HashMap<Integer,List<Integer>>();
    List<Integer> temp = new ArrayList<Integer>();

    int n = 3;
    int area = 1280*720;
    int vposx=0;
    int vposy=0;


    double k = 0.5*(Math.sqrt(area/n));
    for (int i=0; i<=n; i++){
        vposx=ranx.nextInt(1280)+1;
        vposy=rany.nextInt(720)+1;
        temp.add(vposx);
        temp.add(vposy);
        positions.put(i,temp);

    }
        System.out.println(positions);
}
}

结果是这些

{0=[1063, 102, 41, 391, 614, 418, 751, 599], 1=[1063, 102, 41, 391, 614, 418, 751, 599], 2=[1063, 102 , 41, 391, 614, 418, 751, 599], 3=[1063, 102, 41, 391, 614, 418, 751, 599]}

预期的只是0=[randomx,randomy], 2=[randomx,randomy] and so on

【问题讨论】:

    标签: java arraylist hashmap


    【解决方案1】:

    您应该为Map 的每个值创建一个新的ArrayList

    for (int i=0; i<=n; i++){
        List<Integer> temp = new ArrayList<>();
        vposx=ranx.nextInt(1280)+1;
        vposy=rany.nextInt(720)+1;
        temp.add(vposx);
        temp.add(vposy);
        positions.put(i,temp);
    }
    

    否则,您会将Map 中的所有键与相同的值List 相关联。

    【讨论】:

    • 如果List 不需要调整大小。那么Arrays.asList()也可以使用
    • 我的疏忽太可笑了。它完全解决了我的问题。非常感谢!
    • 将此答案标记为已选! @KrowCaw
    【解决方案2】:

    导入 java.util.*;

    公共类 SomeTestingClass {

    public static void main(String[] args) {

    Random ranx = new Random();
    Random rany = new Random();
    HashMap<Integer,List<Integer>> positions=new HashMap<Integer,List<Integer>>();
    List<Integer> temp = null;
    
    int n = 3;
    int area = 1280*720;
    int vposx=0;
    int vposy=0;
    
    
    double k = 0.5*(Math.sqrt(area/n));
    for (int i=0; i<=n; i++){
        vposx=ranx.nextInt(1280)+1;
        vposy=rany.nextInt(720)+1;
        **temp=new ArrayList<Integer>();** // this will solve your problem
        temp.add(vposx);
        temp.add(vposy);
        positions.put(i,temp);
    
    }
        System.out.println(positions);
    

    } }

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2017-09-12
      • 1970-01-01
      • 1970-01-01
      • 2018-06-02
      • 1970-01-01
      • 2017-11-03
      • 2021-10-31
      • 2011-12-16
      相关资源
      最近更新 更多