HashSet<String [ ] > won't add new items | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
+ 1

HashSet<String [ ] > won't add new items

I'm able to find all permutations. And my idea was, to filter out the doubles by adding them to a HashSet. But the Set size is always only 1. Can someone tell me, why this is not working as expected, please? https://code.sololearn.com/cXabLcSUKbzZ/?ref=app

24th Sep 2020, 4:43 PM
Coding Cat
Coding Cat - avatar
7 Answers
+ 2
You're adding the string array "elements" to the set, but HashSet only allows unique elements as determined by Object.equals, and that's not changing on each iteration. No new element is being added (as shown by the false output on all but the first line)
24th Sep 2020, 5:09 PM
Dan Walker
Dan Walker - avatar
+ 2
No problem. A list might be a better option here. Pretty sure array equality is just it's hashcode
24th Sep 2020, 5:26 PM
Dan Walker
Dan Walker - avatar
+ 2
Nice job! Ah I see you're using it to get the unique permutations with repeated elements by excluding duplicates using a set. A couple of minor comments just for brevity - line 26 a new int array is initialized to all 0s in java so don't need the for loop (arrays always initialize to the type default, so boolean[] would all be false, Object[] would all be null etc) Line 32 you could clean up by just doing if(set.add(...)) Instead of making a new variable to track the boolean result. Not required but can tidy it up a little
25th Sep 2020, 9:03 AM
Dan Walker
Dan Walker - avatar
+ 1
Oooh, ok. Now it's clear. The elements of the array and the array it selfs makes the difference 😮. Thanks a lot.
24th Sep 2020, 5:22 PM
Coding Cat
Coding Cat - avatar
+ 1
Oh and by list I meant instead of HashSet :) the array is fine to use otherwise
24th Sep 2020, 5:51 PM
Dan Walker
Dan Walker - avatar
+ 1
Dan Walker Yes, that's what I want to do. Excluding duplicates by using a Set. And thanks for your latest comments 👍
25th Sep 2020, 1:45 PM
Coding Cat
Coding Cat - avatar
0
Dan Walker I had a sleepless night. But now I got it. I have tryed to hash String-Arrays. But there is only one: String[] elements. This is every time the same array. And it can only be one times in the Set. But what I want is to hash the items in the Array. So I have corrected this. Now it works 😀 https://code.sololearn.com/coGnU6M5F4gD/?ref=app
25th Sep 2020, 8:39 AM
Coding Cat
Coding Cat - avatar