首页 > 试题广场 >

MyObject 哪个方法会影响到这段代码的正确性以及效率?

[单选题]
MyObject 哪个方法会影响到这段代码的正确性以及效率?
Map map= new java.util.HashMap();
map.put( "A", new MyObject("A")); 
if ( map.containsValue( new MyObject("A"))) { ... }
  • clone
  • equals
  • hashCode
  • toString

答案是 B equals方法的复写会影响程序效率,因为其中最关键的一句代码是map.containValue()

而这个方法内部实现最终是调用MyObject中的equals方法去判断是否相同,影响效率也是因为equals方***被调用多次如果内部的代码比对过多时间消耗会比较大,源代码如下。

/**

 * Returns <tt>true</tt> if this map maps one or more keys to the
 * specified value.
 *
 * @param value value whose presence in this map is to be tested
 * @return <tt>true</tt> if this map maps one or more keys to the
 *         specified value
 */
public boolean containsValue(Object value) {
    Node<K,V>[] tab; V v;
    if ((tab = table) != null && size > 0) {
        for (int i = 0; i < tab.length; ++i) {
            for (Node<K,V> e = tab[i]; e != null; e = e.next) {
                if ((v = e.value) == value ||
                    (value != null && value.equals(v)))
                    return true;
            }
        }
    }
    return false;
}
发表于 2017-01-26 20:18:08 回复(0)