In the hashmap, I intentionally return 1 as its hashcode, it will make an array of array as its implementation. Then add two Student with same name. When look up s1, it will equals to s2, not s1. why? and if I have to make it equals to s1, what change I should make ?
A Map cannot have two same keys. How does it know if two keys are equals ? By using equals() and hashCode(). Your two objects are equal, and use the same hashCode. So their can be only one of them in the Map.
And still one question, if we have to make s equals to s1, what should we do ?
You have to find a better way to store your students in a map. Don't make them equal just by their first name. Use other information, like student id.
Side note: your equals method is broken. The equals method should return false when null or an object of an incompatible class is given as argument. In your case, s1.equals(null) will throw a NullPointerException instead of returning false; s1.equals("") will throw a ClassCastException. Before doing any casting in the equals method you should have checked for:
- the value being null (== null)
- the value being castable to the right type (instanceof, or the sometimes preferred getClass() == o.getClass()).