I currently have a Set that contains three strings ("car"
, "two dollar"
, "foo"
). I then execute the following against a passed HashMap<String, Double>
.
if (getSet().contains(currentHashMapItem.getKey()) == true) {
System.out.println(currentHashMapItem.getKey());
}
The first key is "car"
, that matches as expected and displays. However, the second key is "dollar"
, but doesn't display. Now my understanding of how contains works is it will return true if the string it is comparing exists in the Set that's being returned in getSet()
, but no dice. Even tried an ArrayList<String>
as well with no luck. Anyone ran into this before? Am I trying to cut too sharp a corner and forced to use a regex or iterator loop?
The problem is that your Set
does not contain "dollar" but "two dollar". Therefore it contains a string which contains the key but does not directly contain the key. As the Set.contains()
method uses .equals()
, this will fail unless the keys are identical.
You can iterate through the set of keys and see if any String.contains()
your key.
As an additional option, you could make a new Set
class with your own contains()
method (either overriding or overloading the current one) which uses the String.contains()
method of comparison instead of .equals()
. This could be done three ways:
Implement the Set
interface
-Convenient and could simply overload the boolean contains(Object)
method with a boolean contains(String)
option (also look at using the AbstractSet
class)
Composition
-Allows use of a distinct type of Set
(such as HashSet
, TreeSet
, etc), instead of the more general interface
Inheritence
-Similar to composition but a less elegant and appropriate option
-Only do this if you have other reasons to want a child class
The key is "two dollar". That does not match "dollar" so the key is not found. To do what you want, you would have to retrieve every key in the set, and use keyString.contains("dollar");
to look for partial matches.
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