-6

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

5
  • You are printing the contents of the HashSet. What different output did you expect?
    – Sören
    Commented Mar 24 at 12:42
  • i like to print all the elements of the set , but looks like my conversion of array to set it not right
    – user63898
    Commented Mar 24 at 12:58
  • 2
    do you really want a HashSet containing arrays, or should it be a HashSet<Integer>? Arrays are not the best elements to be maintained in a HashSet since, for example, arrays do not extend hashcode()
    – user85421
    Commented Mar 24 at 13:19
  • 3
    Please do not upload images of code/data/errors., anything that is represented in textual form is better posted as textt (15 years, 30K reputation??!!)
    – user85421
    Commented Mar 24 at 13:26
  • also check Arrays.asList() not working as it should?
    – user85421
    Commented Mar 24 at 13:33

1 Answer 1

1

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]
5
  • wait the end result is to that the set not to hold array in each element . but convert the elements of the array to set
    – user63898
    Commented Mar 24 at 12:53
  • 6
    I would suggest asking a new question, and this time try to frame the question correctly.
    – jon hanson
    Commented Mar 24 at 12:58
  • You might also do Set<Integer> allInts = result.stream().flatMapToInt(IntStream::of).boxed().collect(Collectors.toSet());
    – g00se
    Commented Mar 24 at 13:32
  • no easier way ? im not going to remember this
    – user63898
    Commented Mar 24 at 16:37
  • StackOverflow in a nutshell...
    – jon hanson
    Commented Mar 24 at 22:40

Not the answer you're looking for? Browse other questions tagged or ask your own question.