Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Checking containment in a Set of strings in Java

Tags:

java

string

set

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?

like image 632
athena Avatar asked Nov 26 '10 11:11

athena


People also ask

How do you check if a set contains a String in Java?

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.

How do I check if a String contains?

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.

How do you check if a String contains a character?

The contains() method checks whether a string contains a sequence of characters. Returns true if the characters exist and false if not.


1 Answers

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)

like image 105
Ralph Avatar answered Sep 29 '22 11:09

Ralph