java中HashSet中的Arrays.asList

问题描述 投票:0回答:2

我必须收集整数列表的列表,并确保其中没有重复项。

我正在使用哈希集来确保该列表中没有重复项。

基本上

Set<List<Integer>> set = new HashSet<>();
List<List<Integer>> list = new ArrayList<>();

我看到,如果我将列表作为

Arrays.asList(1,2,3)
放入 HashSet,HashSet 将确保另一个包含内容
1,2,3
的列表不会出现在集合中。但如果我基本上把它作为一个新的 List 对象

List<Integer> temp = new ArrayList<Integer>()
temp.add(1);
temp.add(2);
temp.add(3);

set 允许重复列表。

据此,我了解到 Set 进行对象比较,而不是列表情况下的值比较。

Arrays.asList(1,2,3)
如何确保集合中没有重复项?

java arrays equals hashset
2个回答
0
投票

Arrays.asList
new ArrayList<Integer>
创建不同类型的对象,这可能就是
HashSet
将它们视为不相等的原因。

尝试:

import java.util.*;
public class Test {
    public static void main(String[] args) {
        List<Integer> a = new ArrayList<Integer>();
        List<Integer> b = Arrays.asList(1,2,3);
        System.out.println(a.getClass());
        System.out.println(b.getClass());
    }
}

-1
投票

ArrayListCollection都不对其HashCode的计算方式做出任何保证,因此这最终将取决于您特定的JVM。

© www.soinside.com 2019 - 2024. All rights reserved.