zaz
zaz

Reputation: 505

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 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

Answers (3)

Alexey
Alexey

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

Paul Bellora
Paul Bellora

Reputation: 55213

Arrays don't override equals and hashCode, and so the HashSet will compare them based on reference equality only. Consider using Lists 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

Jeffrey
Jeffrey

Reputation: 44808

Use a Set<List<String>>. You can use Arrays.asList and List.toArray for conversions, as necessary.

Upvotes: 8

Related Questions