Reputation: 505
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.
Upvotes: 24
Views: 21585
Reputation: 9447
If you really need Set<String[]>
, there is no easy and elegant way for that, AFAICT. The problem is that arrays do not not override equals()
and hashCode()
, on the one hand. On the other hand HashSet
class do not provide a possibility to pass some "strategy" to it that would implement hash code and equality computation externally (something like Comparator
). So you might consider creating TreeSet
with a custom comparator. Unfortunately, I don't know of any implementation of array comparator, so most likely you will need to write your own.
If it's ok for you to have Set<List<String>>
, you can consider advice in other answers.
Upvotes: 4
Reputation: 55213
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.
Upvotes: 37
Reputation: 44808
Use a Set<List<String>>
. You can use Arrays.asList
and List.toArray
for conversions, as necessary.
Upvotes: 8