Creating a set of arrays in java

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 need to encode my own implementation? Adding an object to Set checks the object using equals (), which does not work for arrays.

+7
java arrays set
source share
3 answers

Arrays do not override equals and hashCode , so a HashSet will only compare them based on referential equality. Use List instead:

 Set<List<String>> strSet = new HashSet<List<String>>(); 

In the List.equals documentation:

Returns true if and only if the specified object is also a list, both lists are the same size, and all the corresponding pairs of elements in two lists are equal.

+12
source share

Use Set<List<String>> . You can use Arrays.asList and List.toArray if necessary.

+6
source share

If you really need Set<String[]> , there’s no easy and elegant way to do this, AFAICT. The problem is that arrays do not override equals() and hashCode() , on the one hand. On the other hand, the HashSet class does not provide the ability to pass some β€œstrategy” for it, which will implement a hash code and equality computation from the outside (something like Comparator ). Therefore, you can create a TreeSet using a special comparator. Unfortunately, I do not know any implementation of an array comparator, so most likely you will need to write your own.

If you are comfortable having Set<List<String>> , you can consider the advice in other answers.

0
source share

All Articles