无法在java中打印简单的HashSet<int[]>元素[重复]

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

我尝试在 java 20 中打印简单的 HashSet 但没有成功,我在这里缺少什么?

public static void main(String[] args) {
    int[] a1 = {1,3,6,8,10,11,14,17,21};
    int[] a2 = {2,4,8,9,12,14,15};

    
    HashSet<int[]> result = new HashSet<>(Arrays.asList(a1));
    Iterator<int[]> it = result.iterator();
    while(it.hasNext()){
      System.out.println(it.next());
    }
    System.out.println(result.toString());
   

  }
}

结果是:

java hashset println
1个回答
1
投票

要获取数组的字符串表示形式,您可以使用

Arrays.toString()
:

    public static void main(String[] args) {
        int[] a1 = {1,3,6,8,10,11,14,17,21};
        int[] a2 = {2,4,8,9,12,14,15};

        Set<int[]> set = new HashSet<>();
        set.add(a1);
        set.add(a2);

        for(int[] entry : set) {
            System.out.println(Arrays.toString(entry));
        }
    }

输出:

[2, 4, 8, 9, 12, 14, 15]
[1, 3, 6, 8, 10, 11, 14, 17, 21]
© www.soinside.com 2019 - 2024. All rights reserved.