3 ms·
boolean hasName(String storedName) { return getLoadNames().\ contains(storedName); } > That’s it. No more looping, just a simple check. A
by e12e 9y ago
boolean hasName(String
storedName) {
return getLoadNames().\
contains(storedName);
}
> That’s it. No more looping, just a simple check.
And how is set.contains implemented?
https://github.com/openjdk-mirror/jdk7u-jdk/blob/master/src/share/classes/java/util/HashSet.java https://github.com/openjdk-mirror/jdk7u-jdk/blob/master/src/...
wraps
https://github.com/openjdk-mirror/jdk7u-jdk/blob/master/src/share/classes/java/util/HashMap.java https://github.com/openjdk-mirror/jdk7u-jdk/blob/master/src/...
public boolean contains(Object o) { return map.containsKey(o); // map is HashMap }
public boolean containsKey(Object key) { return getEntry(key) != null; }
And finally:
final Entry<K,V> getEntry(Object key) {
int hash = (key == null) ? 0: \
hash(key.hashCode());
for (Entry<K,V> e = \
table[indexFor(hash, \
table.length)];
e != null;
e = e.next) {
Object k;
if (e.hash == hash &&
((k = e.key) == key \
|| (key != null \
&& key.equals(k))))
return e;
}
return null;
}
TL;DR how did they imagine a general setContains would be implemented without a loop?
[ed: obviously it makes sense to use a datastructure that more closely match your intent, but the wording here struck me as a bit odd...]