Adam Davis
Posts: 2
Nickname: adavis
Registered: Sep, 2003
|
|
Re: overriding methods in java.lang.object
|
Posted: Oct 1, 2003 10:34 AM
|
|
> > First of all is there any real requirement to override > > these methods? ...snip... > The problem description is something like this.. > since we have to use the keys in the hashmap as the > objects themselves, we should override the equals and > hashcode methods..and we have to do a directory search > given the first and last names.
Here is an excerpt of what I have done in the past. I'm not an expert, so I welcome any comments on the pros and cons of this approach.
public class DailyNotes implements Cloneable, Comparable, Serializable { protected Date day; protected String notes;
...
/* Interface methods */
public int compareTo(Object o) throws ClassCastException { if (o instanceof DailyNotes) { int res= this.day.compareTo( ((DailyNotes)o).getDay() ); if (res == 0) { return( this.notes.compareTo( ((DailyNotes)o).getNotes()) ); } else { return(res); } } else { throw new ClassCastException("Error: Could not compare an object of Class " + o.getClass().getName() + " to a DailyNotes object"); } } /* Overridden methods */
public boolean equals(Object o) { if (o instanceof DailyNotes) { return( this.compareTo((DailyNotes)o) == 0 ); } else { return(false); } }
public int hashCode() { return( this.day.hashCode() ); }
public String toString() { return( DateFormat.getDateInstance(DateFormat.MEDIUM).format(day) ); }
...
}
In my program, DailyNotes objects are stored in an ArrayList and accessed randomly by date or sequentially in date order.
|
|