1

当java从hashmap调用get方法时java会执行equals()比较吗?

我读过它确实如此,但是由于我遇到的错误,它似乎在进行 == 比较。

公共类 UniversalFiniteStateAutomaton {

State currentState;
State initialState;
State trapState;

public UniversalFiniteStateAutomaton(ArrayList<String> finalStates,
        ArrayList<String> transitions) {
    String statesAndTransitions[];
    Map<Symbol<E>, State> createdStates = new HashMap<Symbol<E>, State>();
    for (String s : transitions) {
        // Replace the stuff that doesn't matter
        s = s.replaceAll("[()]", "");
        // Split the transition into states and transitions
        statesAndTransitions = s.split("\\s+");

        // Create the state if its not already created
        if (finalStates.contains(new Symbol(statesAndTransitions[0]))) {
            if (!createdStates.containsKey((new Symbol(statesAndTransitions[0])))) {
                createdStates.put(new Symbol(statesAndTransitions[0]),
                        new FinalState(this));
                System.out.println("Created one symb " + new Symbol(statesAndTransitions));
            }
        } else {
            if (!createdStates.containsKey(new Symbol(statesAndTransitions[0]))) {
                createdStates.put(new Symbol(statesAndTransitions[0]),
                        new NormalState(this));
                System.out.println("Created one symb " + new Symbol(statesAndTransitions[0]));
            }
        }
        // Make sure that the next state is created
        if (finalStates.contains(new Symbol(statesAndTransitions[2]))) {
            if (!createdStates.containsKey(new Symbol(statesAndTransitions[2]))) {
                createdStates.put(new Symbol(statesAndTransitions[2]),
                        new FinalState(this));
            }
        } else {
            if (!createdStates.containsKey(new Symbol(statesAndTransitions[2]))) {
                createdStates.put(new Symbol(statesAndTransitions[2]),
                        new NormalState(this));
            }
        }

        System.out.println(createdStates);
        // Define the transition
        createdStates.get(new Symbol(statesAndTransitions[0])).addTransition(
                new Symbol(statesAndTransitions[1]),
                createdStates.get(new Symbol(statesAndTransitions[2])));

    }
    this.currentState = createdStates.get(new Symbol("0"));
}

public String analyzeInput(String input) {
    String splitInput[] = input.split("\\s+");
    for(String s: splitInput)
        try {
            currentState.transition(new Symbol(s));
        } catch (TrapException e) {
            return("Reject");
        }
    if(currentState.type()==0)
        return "Accept";
    return "Reject";
}


public void setState(State currentState) {
    this.currentState = currentState;
}
 }




public class Symbol<E> {
private E symbol;

public Symbol(E symbol){
    this.symbol = symbol;
}

public E getSymbol() {
    return symbol;
}

public void setSymbol(E symbol) {
    this.symbol = symbol;
}

public String toString(){ return "" +symbol;}

}

4

6 回答 6

3

是的,它确实。但是,如果您没有equals()为自己的类定义自己的类,它会使用Object.equals(),并且确实会使用==。这就是为什么如果你想把你的对象放入一个集合中,你应该重写equals()(and )。hashcode()

于 2012-04-23T08:47:31.507 回答
3

你自己看:

于 2012-04-23T08:48:28.370 回答
2

它使用 hashcode() 来定位潜在的匹配,然后使用 equals 来找到精确匹配。如果其用户定义的对象,请确保实现 equals 和 hashcode 以遵守合同(在 Object 的类文档中提到)。

于 2012-04-23T08:47:35.737 回答
1

get first 使用 == 检查它是否是同一个对象。如果不是,它使用等于。

请参阅此处的代码 http://www.docjar.com/html/api/java/util/HashMap.java.html

/**
  298        * Returns the value to which the specified key is mapped,
  299        * or {@code null} if this map contains no mapping for the key.
  300        *
  301        * <p>More formally, if this map contains a mapping from a key
  302        * {@code k} to a value {@code v} such that {@code (key==null ? k==null :
  303        * key.equals(k))}, then this method returns {@code v}; otherwise
  304        * it returns {@code null}.  (There can be at most one such mapping.)
  305        *
  306        * <p>A return value of {@code null} does not <i>necessarily</i>
  307        * indicate that the map contains no mapping for the key; it's also
  308        * possible that the map explicitly maps the key to {@code null}.
  309        * The {@link #containsKey containsKey} operation may be used to
  310        * distinguish these two cases.
  311        *
  312        * @see #put(Object, Object)
  313        */
  314       public V get(Object key) {
  315           if (key == null)
  316               return getForNullKey();
  317           int hash = hash(key.hashCode());
  318           for (Entry<K,V> e = table[indexFor(hash, table.length)];
  319                e != null;
  320                e = e.next) {
  321               Object k;
  322               if (e.hash == hash && ((k = e.key) == key || key.equals(k)))
  323                   return e.value;
  324           }
  325           return null;
  326       }
于 2012-04-23T08:49:47.077 回答
1

hashCode()用于比较 - http://www.docjar.com/html/api/java/util/HashMap.java.html

于 2012-04-23T08:55:31.563 回答
0

Hashmap 使用 hashcode() 首先找到合适的桶,如果它在桶中找到多个条目,则使用 equals 方法。

如果您没有根据您的要求在您的类中定义 equals 方法,那么它将使用父类 Object 的定义,这是简单的“==”操作。

如果您使用您的类作为 hashmap 中的键,则最好覆盖 hashcode 和 equals 方法。

于 2014-12-13T17:59:16.623 回答