I am trying to test whether two HashSets
of Strings
contain identical Strings
. The retainAll()
method of Java Sets (which, as I understand it, implements the Collection interface) is a good way to check the intersection of two Sets. However, this method seems to test for equality using the ==
style check for whether they are references to the same memory object, rather than using the String's equals()
method to check whether the contents are the same. Is there a way to get something the works like retainAll but that uses the equals()
method?
I am trying to write code that checks whether a String contains a substring over a certain length from a certain other String. My strategy was to create a HashSet of each String containing all substrings of that length, then check whether the Sets contain Strings in common.
My current solution was to create my own static method that does what I want the retainAll method to do.
static boolean containsEqualElement(Set SetOne, Set SetTwo) {
Iterator it = SetOne.iterator();
while (it.hasNext()) {
Object thisComp = it.next();
Iterator it2 = SetTwo.iterator();
while (it2.hasNext()) {
if (it2.next().equals(thisComp)) {
return true;
}
}
}
return false;
}
I'm not sure how the efficiency of this method compares to the retainAll method.