gpt4 book ai didi

java - 如何动态创建HashMap

转载 作者:行者123 更新时间:2023-11-29 06:37:00 24 4
gpt4 key购买 nike

我有以下方式的 5L 值(行)的 .txt 文件,还有分区大小 50000

 1
3
-1546.9
-67.90
3456
.
.
.

通过以下示例,您可以理解我的观点中的分区的含义。

将文件数据导入list后可以看到如下图

 importingdata={1,2,3,4,5,.........500000};

分区后可以看到如下图

PartitionList={{1,2,3,...50000},{50001,....,100000},{100001,......,150000},...{450000,.....500000}};

partitionList 数据类型是 ArrayList<HashMap<Integer,Double>> 。这意味着 partitionlist 的所有子列表都是 HashMap<Integer,Double>

所有 HashMap 列表的键值都从 1 to 50000 开始。如下所示。

     PartitionList={{1->1,2->2,3->3,...,50000->50000},{1->50001,.....,50000->100000},{1->100001,....,50000->150000},...,{1->450000,.....,50000->500000}};

我想在导入文件的时候按照上面的方式整理文件数据。

为此,我尝试使用示例代码,但它不起作用。

public static void main(String[] args) {
ArrayList<HashMap<Integer, Double>> finalList=new ArrayList<>();
HashMap<Integer, Double> hash1=new HashMap<>();
hash1.put(1, 1.0);
hash1.put(2, 2.0);
hash1.put(3, 3.0);
finalList.add(hash1);
System.out.println(finalList.size());
System.out.println(hash1.size());
hash1.clear();
System.out.println(hash1.size());
hash1.put(1, 1.0);
hash1.put(2, 2.0);
hash1.put(3, 3.0);
finalList.add(hash1);
System.out.println(finalList.size());
System.out.println(hash1.size());
hash1.clear();
System.out.println(hash1.size());
HashMap<Integer, Double> hash2=finalList.get(1);
HashMap<Integer, Double> hash3=finalList.get(2);
System.out.println(hash2.size());
System.out.println(hash3.size());
}

我希望你们明白我在尝试什么。在这里我提到了 5L 行,但在我的实际情况中,我正在处理 80L 所以建议我使用优化代码。

谢谢

最佳答案

HashMap 是可变的! hashMap 引用仍然相同。当您这样做时:

hash1.clear();

您清除原始 map 实例。这意味着,您放入列表中的 map 实例将被清除。

你应该做的

hash1 = new HashMap<Integer, Double>();

相反。这会更新变量对 HashMap() 的新实例的引用。

关于java - 如何动态创建HashMap,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19131213/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com