16. When providing a user defined key class for storing objects in the Hashmaps or Hashtables, what methods do you have to provide or override


You should override the equals() and hashCode() methods from the Object class. The default implementation of the equals() and hashcode(), which are inherited from the java.lang.Object uses an object instance’s memory location (e.g. MyObject@6c60f2ea). This can cause problems when two instances of the car objects have the same colour but the inherited equals() will return false because it uses the memory location, which is different for the two instances. Also the toString() method can be overridden to provide a proper string representation of your

object. Points to consider:

  • If a class overrides equals(), it must override hashCode().

  • If 2 objects are equal, then their hashCode values must be equal as well.

  • If a field is not used in equals(), then it must not be used in hashCode().

  • If it is accessed often, hashCode() is a candidate for caching to enhance performance.

Note: Java 1.5 introduces enumerated constants, which improves readability and maintainability of your code. Java programming language enums are more powerful than their counterparts in other languages. E.g. A class like Weather can be built on top of simple enum type Season and the class Weather can be made immutable, and only one instance of each Weather can be created, so that your Weather class does not have to override equals() and hashCode() methods.

public class Weather {

public enum Season {WINTER, SPRING, SUMMER, FALL}

private final Season season;

private static final List listWeather = new ArrayList ();

private Weather (Season season) { this.season = season;}

public Season getSeason () { return season;}

static {

for (Season season : Season.values()) {

listWeather.add(new Weather(season));

}

}

public static ArrayList getWeatherList () { return listWeather; }

public String toString(){ return season;} // takes advantage of toString() method of Season.

}


1 comment: