I want to make a simple note reminder app that uses hashMap when the date is the key and the value is the text. I have a Panel class(GUI), the hash-table class (Reminder.java), and a "MyDateClass.java" that represent a date for my purposes.
My gui is made of 3 JComboBox (day,month,year), One text area and 2 buttons - "Save", "Load".
The 2 buttons in the GUI Panel:
butSave.addActionListener(new ActionListener () { public void actionPerformed(ActionEvent e) { MyDateClass chosenDate = new MyDateClass(cbYear.getSelectedIndex()+2013,cbMonth.getSelectedIndex()+1, cb.getSelectedIndex()+1); if(!remind.isReminderExists(chosenDate)){ remind.save(chosenDate, tfReminder.getText()); System.out.println("reminder doesnt exists"); }} }); butLoad.addActionListener(new ActionListener () { public void actionPerformed(ActionEvent e) { System.out.println("tryin to load"); MyDateClass chosenDate = new MyDateClass(cbYear.getSelectedIndex()+2013,cbMonth.getSelectedIndex()+1, cb.getSelectedIndex()+1); if(remind.isReminderExists(chosenDate)){ remind.Load(chosenDate); System.out.println("reminder exists"); }} }); Reminder class:
public class Reminder { Map<MyDateClass,String> reminderMap; public Reminder(){ reminderMap = new HashMap<MyDateClass,String>(); } public boolean isReminderExists(MyDateClass date){ return reminderMap.containsKey(date); } public void save(MyDateClass date, String Input){ System.out.println("Trying to save"); reminderMap.put(date, Input); } public void Load(MyDateClass date){ System.out.println("Trying to load"); String output; output = reminderMap.get(date); System.out.println(output); } So after i push the save button i get from the console:
Trying to save reminder doesnt exists But then i push the Load button for the same date and
if(remind.isReminderExists(chosenDate)) Isnt triggerd.
What might be the problem?
Do i need to override hashCode() and equals() ? I genereted them but i dont if and how to change the equals() (do i need to manipulate it to compare both dates? How do i do that if "this" refers to the reminder Object)
hashCodeandequals.equalsneeds to return true if your objects are conceptually equal, andhashCodeneeds to return a consistent value for a given set your object contents, such that allequalsobjects will have the samehashCode.MyDateClasscode.