I have a Set of String[]. I want to check whether this Set contains another String[].
Set<String[]> s = new HashSet<String[]>();
s.add(new String[] {"lucy", "simon"});
System.out.println(s.contains(new String[] {"lucy", "simon"}));
However, false is printed. My guess is this is because only the references are being compared and not the actual Strings. It seems, the only option I have is to create a class, say Phrase, and implement hashCode()
and equals()
(that use Arrays.hashCode(...)
).
Is there any other way to achieve what I want?
Set contains() method in Java with Examples util. Set. contains() method is used to check whether a specific element is present in the Set or not. So basically it is used to check if a Set contains any particular element.
contains() method searches the sequence of characters in the given string. It returns true if sequence of char values are found in this string otherwise returns false.
The contains() method checks whether a string contains a sequence of characters. Returns true if the characters exist and false if not.
Your guess is correct: arrays ([]) do not implement a deep equals method: they are equals if they are the same instance.
The simplest solution would be: replacing String[]
by List<String>
An other way (but i do not recommend it) is to implement your own Set, which does not based on Object.equals
but on java.util.Arrays.equals(Object[]a, Object[]b)
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