开发者

Simple Java Map puzzle [closed]

开发者 https://www.devze.com 2022-12-10 04:45 出处:网络
It's difficult to tell what is being asked here. This question is ambiguous, vague, incomplete, overly broad, or rhetorical andcannot be reasonably开发者_JAVA百科 answered in its current form.
It's difficult to tell what is being asked here. This question is ambiguous, vague, incomplete, overly broad, or rhetorical and cannot be reasonably开发者_JAVA百科 answered in its current form. For help clarifying this question so that it can be reopened, visit the help center. Closed 13 years ago.

What is the best implementation for this general-purpose library method?

public static <K, V> boolean containsEntry(
    Map<K, V> map, K key, V value) {}

Criteria for judging this puzzle, as with most coding puzzles, are in this order:

  1. Completeness
  2. Correctness
  3. Performance
  4. Beauty
  5. Receipt of PayPal contribution

EDIT:

Well, since it got closed, I might as well post the answer. I think this is probably optimal:

  V valueForKey = map.get(key);
  return (valueForKey == null)
      ? value == null && map.containsKey(key)
      : valueForKey.equals(value);

A clever simple solution would be:

  return map.entrySet().contains(
      new AbstractMap.SimpleImmutableEntry<K, V>(key, value));

It does allocate an instance, but it gives the map implementation a little more opportunity to do something optimal.


public static <K, V> boolean containsEntry(Map<K, V> map, K key, V value) {
    returns map.containsKey(key) && isEqual(map.get(key), value);
}
private static boolean isEqual(Object a, Object b) {
    return a == null ? a == b : a.equals(b);
}

Copied from deleted post.


public static <K, V> boolean containsEntry(Map<K, V> map, K key, V value) {
    returns map.containsKey(key) & isEquals(map.get(key), value);
}
private static boolean isEqual(Object a, Object b) {
    return a == null ? a == b : a.equals(b);
}

You can also inline isEqual method.


Presumably it's meant to return a boolean:

public static <K, V> boolean containsEntry(Map<K, V> map, K key, V value) {
    return map.containsKey(key) && map.get(key).equals(value);
}
0

精彩评论

暂无评论...
验证码 换一张
取 消