gpt4 book ai didi

java - 在Java中,存储大型列表的最有效内存方式是什么

转载 作者:行者123 更新时间:2023-12-02 04:56:04 28 4
gpt4 key购买 nike

我必须比较两个大的整数数组(大约 150,000 个值),看看哪些值是唯一的,哪些不是。我希望输出存储在三个数据结构中:UniqueTo_A、UniqueTo_B 和 SharedElements。我通常会使用 ArrayList 之类的东西来进行此类操作,因为可以临时添加值,但是我知道对于 ArrayList 来说,add() 和 remove() 的开销相当大。所以我的问题是:-在Java中,存储大型列表的最有效内存方式是什么,可以动态添加项目,性能是关键。所有帮助或评论将不胜感激。

编辑:感谢您的参与。 TheLostMind,我需要添加到数据集,但哈希集将有助于这一点,所以我将继续使用哈希集。 Nafas + NeplatnyUdaj 感谢您提供示例。埃克尔斯,我应该掌握 Collection ,我会研究这个以供下次使用。后续实现....

最佳答案

使用Set,因为它在恒定时间内添加,它在恒定时间内删除多个值。我每天使用 set 来存储超过数百万个对象。和 removeAll 仍然以毫秒为单位

Set<Integer> setA= new HashSet<Integer>();
Set<Integer> setB= new HashSet<Integer>();

//add stuff to setA and setB by add() method

Set<Integer> uniqueToA=new HashSet<Integer>(setA);
Set<Integer> uniqueToB=new HashSet<Integer>(setB);
Set<Integer> shared=new HashSet<Integer>();
shared.addAll(setA);
shared.addAll(setB);

uniqueToA.removeAll(setB);
uniqueToB.removeAll(setA);

shared.removeAll(uniqueToA);
shared.removeAll(uniqueToB);

System.out.println(uniqueToA); //unique to A
System.out.println(uniqueToB); //unique To B
System.out.println(shared); //shared

关于java - 在Java中,存储大型列表的最有效内存方式是什么,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28764513/

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