get()如何在hashmap上工作

时间:2012-04-23 08:43:29

标签: java hashmap

当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;}

}

6 个答案:

答案 0 :(得分:3)

是的。但是,如果您没有为自己的班级定义自己的equals(),则会使用Object.equals() 使用==。这就是为什么你应该覆盖equals()(和hashcode()),如果你想把你的对象放到一个集合中。

答案 1 :(得分:3)

答案 2 :(得分:2)

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

答案 3 :(得分:1)

首先使用==来检查它是否是同一个对象。如果不是,则使用等于。

请参阅此处的代码 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       }

答案 4 :(得分:1)

答案 5 :(得分:0)

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

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

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