Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Creating a Set of Arrays in java

Tags:

java

arrays

set

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.

like image 541
zaz Avatar asked Jul 12 '13 03:07

zaz


People also ask

Can you make a set of arrays in Java?

Java Array to Set We can convert an array into List using Arrays. asList() method, then use it to create a Set.

Can I create a set of array?

Create the Set by passing the Array as parameter in the constructor of the Set with the help of Arrays. asList() method.

How do you create an array of sets?

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.

How do you add an array to a set in Java?

int[] arr = { 2, 6, 4 , 2, 3, 3, 1, 7 }; Set<Integer> set = new HashSet<Integer>( ); Collections.


1 Answers

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.

like image 98
Paul Bellora Avatar answered Sep 25 '22 16:09

Paul Bellora