Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Enum as key of HashTable

I'm writting a Schedule structure in Java. I have a Hashtable with enum Day as Key and list of timeranges as value. Like this :

public enum Day {
    SUNDAY, MONDAY, TUESDAY, WEDNESDAY,
    THURSDAY, FRIDAY, SATURDAY 
}

private Hashtable<Day,TimeRanges> _applyCalendar; 

where TimeRanges class is ...

public class TimeRanges implements List<TimeRange> {

When I add elements to _appleCalendar I do this :

public void addApplyDay(Day day,TimeRanges trs) {
    if (! _applyCalendar.contains(day)) {
        _applyCalendar.put(day, trs);
    } else {
        for ( TimeRange t : trs) {
            _applyCalendar.get(day).add(t);
        }
    }

}

My problem is method contains() doesn't work right. HashTable can't be able to found existing element in hashtable,all time enter in the first condition :S

Is there any way to do this without should to declare Day as class and implement comareTo() ??

like image 439
arturn Avatar asked Oct 08 '22 17:10

arturn


1 Answers

I think you want to use .containsKey() instead of contains(). contains() will search the actual objects whereas containsKey() will search the keys.

public void addApplyDay(Day day,TimeRanges trs) {
    if (! _applyCalendar.containsKey(day)) { // << use containsKey
        _applyCalendar.put(day, trs);
    } else {
        for ( TimeRange t : trs) {
            _applyCalendar.get(day).add(t);
        }
    }

}
like image 93
Matt MacLean Avatar answered Oct 12 '22 12:10

Matt MacLean