Can't print simple HashSet<int[]> elements in java

71 Views Asked by At

I try to print simple HashSet in java 20 without success what am i missing here ?

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());
   

  }
}

Result is :
enter image description here

1

There are 1 best solutions below

5
jon hanson On

To get a string representation of an array you can use 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));
        }
    }

Output:

[2, 4, 8, 9, 12, 14, 15]
[1, 3, 6, 8, 10, 11, 14, 17, 21]