Azodious Azodious - 7 days ago 5
Java Question

Designing single API for two different types

I've two lists:

List<Date> list1 = new ArrayList<Date>();
List<WDate> list2 = new ArrayList<WDate>();


I want to remove some objects from these lists. This functionality is present in a util class.

public static List<Date> removeFromList1(List<Date> dateList)
{
Iterator<Date> dateItr = dateList.iterator();
while(dateItr.hasNext())
{
Date date = dateItr.next();
if(date.compareTo(currentDate) <= 0)
dateItr.remove();
}

return dateList;
}

public static List<WDate> removeFromList2(List<WDate> dateList)
{
Iterator<WDate> dateItr = dateList.iterator();
while(dateItr.hasNext())
{
WDate date = dateItr.next();
if(date.getDate().compareTo(currentDate) <= 0)
dateItr.remove();
}

return dateList;
}

class WDate
{
Date date;
Date getDate() { return date;}
}


How to create a single utility method to serve both the lists?

Answer

Here is a possible solution:

public static <T extends Comparable<T>> List<T> removeFromList(List<T> list, T current) 
{
    Iterator<T> itr = list.iterator();
    while(itr.hasNext())
    {
        T elm = itr.next();
        if(elm.compareTo(current) <= 0)
            itr.remove();
    }

    return list;
}

...

class WDate implements Comparable<WDate>
{
    Date date;
    Date getDate() { return date;}

    public WDate(Date date) {
        this.date = date;
    }
    @Override
    public int compareTo(WDate other) {
        return date.compareTo(other.date);
    }
}

UPDATE:

If you want to avoid implementing the Comparable interface, you can supply a Comparator to removeFromList:

public static <T> List<T> removeFromList(List<T> list, T current,
        Comparator<T> comp) {
    Iterator<T> itr = list.iterator();
    while(itr.hasNext())
    {
        T elm = itr.next();
        if(comp.compare(elm, current) <= 0)
            itr.remove();
    }
    return list;
}