Lightyear Buzz
Lightyear Buzz

Reputation: 796

How does get() work on hashmap

When java calls the get method from hashmap does java perform a equals() comparison?

I've read that it does but with the errors I'm getting, it seems like its doing a == comparison.

public class 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;}

}

Upvotes: 1

Views: 1132

Answers (6)

Panther
Panther

Reputation: 3339

Hashmap uses the hashcode() to find the appropirate bucket first and if it finds more than one entry in bucket then it used equals method.

If you are not defining equals method in your class as per your requirment than it will use the defination from parent class Object, which is simple "==" operation.

It is always preferable to override hashcode and equals method if you are using your class as key in hashmap.

Upvotes: 0

scibuff
scibuff

Reputation: 13755

It uses the hashCode() for the comparison - http://www.docjar.com/html/api/java/util/HashMap.java.html

Upvotes: 1

Alexander
Alexander

Reputation: 48262

get first uses == to check that maybe it's the same object. If not it uses equals.

See the code here 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       }

Upvotes: 1

Ashwinee K Jha
Ashwinee K Jha

Reputation: 9307

It uses hashcode() to locate potential matches and then uses equals to find exact match. If its user defined object make sure that both equals and hashcode are implemented to honor the contract (mentioned in Class documentation of Object).

Upvotes: 2

Kilian Foth
Kilian Foth

Reputation: 14346

Yes it does. However, if you don't define your own equals() for your own class, it uses Object.equals(), and that does use ==. This is why you should override equals() (and hashcode()) if you ever want to put your objects into a Collection.

Upvotes: 3

Related Questions