gpt4 book ai didi

java - 使用 HashSet 时如何保持插入顺序?

转载 作者:行者123 更新时间:2023-12-01 06:01:41 25 4
gpt4 key购买 nike

我需要维护集合中最近插入的订单。

Set<Intger> s = new HashSet<>();
s.add(1);
s.add(2);
s.add(3);
s.add(1);
print(s);

使用 LinkedHashSet() 时,顺序为 (1,2,3)。我想要的顺序是(2,3,1)。我想要一种有效的方法来将集合的属性与堆栈的属性结合起来。

最佳答案

很简单,做一个方法来判断集合是否有需要添加的值,如果是删除它然后添加它,如果不添加它就添加它。

这就是方法。

package exercise.setInsertionOrder;

import java.util.LinkedHashSet;
import java.util.Set;

public class SetInsertionOrder {

public static void main(String[] args) {
Set<Integer> s = new LinkedHashSet<>();
/*s.add(1);
s.add(2);
s.add(3);
s.add(1);*/
addByJudgeValueIsAdded(s, 1);
addByJudgeValueIsAdded(s, 2);
addByJudgeValueIsAdded(s, 3);
addByJudgeValueIsAdded(s, 1);
System.out.println(s);
}


public static <T> void addByJudgeValueIsAdded(Set<T> set,T t){
if(set.contains(t)){
set.remove(t);
set.add(t);
}else{
set.add(t);
}
}

}
<小时/>

这就是结果。

[2, 3, 1]

关于java - 使用 HashSet 时如何保持插入顺序?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56894134/

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