2
import java.util.HashMap;
import java.util.Map;

public class StudentTest {
    public static final class Student {
        public Student( String name ) {
            this.name = name;
        }
        private String name;
    }

    public static void main(final String[] args ) {
        Map<Student, String> map = new HashMap<>();
        map.put( new Student( "john"), "present" );
        System.out.println( map.get( new Student( "john" ) ) );
    }

I know how to make this work by changing the main function and initializing the object but is it possible to achieve the result without touching the main? I was asked this in an interview.

I have spent a lot of time googling but haven’t been able to get close to the answer. I’m not even sure what should be my search parameters anymore. Please help.

2 Answers2

3

You have 2 different student object used while putting to and getting from HashMap. So you were not able to print "present".

So you can override 2 methods in Student class, equals and hashcode such that when name is equal it equals should return true and hashcode should return same value.

That's it, your are done. You will get "present"

Overriding just equals is not fully correct answer. There is contract "Equal objects should always return same hashcode"

So overriding equal and hashcode is the clean way

Pavan
  • 819
  • 6
  • 18
1

You need to override the equals(Object o) method in class Student. As default in java, the equals method just check if the objects are exactly the same, create with one new expression. To change it, override the equals method to compare the name of the students. For example:

public boolean equals(Object o){
    if(o instanceof Studet){
        return this.name.equals(((Student)o).name);
    }
    return false;
}

And, because of java contract, you should override hashCode like this:

public int hashCode(){
    return this.name.hashCode();
}
Programmer
  • 803
  • 1
  • 6
  • 13
  • Thank you, with the edit, this is answer is accurate as well. Worked perfectly. Note that your first snippet says `instaceof` instead of `instanceof` and `Studet` instead of `Student` – Sanket kumar Jan 31 '21 at 07:12