I want to do something like
Set <String[]> strSet = new HashSet <String[]> ();
Is there an easy way to make a Set of arrays in Java, or do I have to code my own implementation? Adding an object to a Set checks the Object using equals(), which does not work for arrays.
Java Array to Set We can convert an array into List using Arrays. asList() method, then use it to create a Set.
Create the Set by passing the Array as parameter in the constructor of the Set with the help of Arrays. asList() method.
Create a Set object. Add elements to it. Create an empty array with size of the created Set. Convert the Set to an array using the toArray() method, bypassing the above-created array as an argument to it.
int[] arr = { 2, 6, 4 , 2, 3, 3, 1, 7 }; Set<Integer> set = new HashSet<Integer>( ); Collections.
Arrays don't override equals
and hashCode
, and so the HashSet
will compare them based on reference equality only. Consider using List
s instead:
Set<List<String>> strSet = new HashSet<List<String>>();
From the List.equals
documentation:
Returns
true
if and only if the specified object is also a list, both lists have the same size, and all corresponding pairs of elements in the two lists are equal.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With