Home > Net >  Method to return the same interface implementation as passed in
Method to return the same interface implementation as passed in

Time:12-24

I've seen similar questions, but I don't really feel like I have an understanding of how to solve this. I want to make a method that takes a list of any class that implements an interface and returns an object of the same class.

I was hoping something like this would work.

public interface IHasDate {
  public Date getDate();
}

public class A implements IHasDate {
  private Date date;
  public Date getDate(){ return date; }
}

public class B implements IHasDate {
  private Date date;
  public Date getDate(){ return date; }
}

public class Util {
  public IHasDate getUpcoming(List<IHasDate> dates) {
    // logic omitted to find the object with the next upcoming date
    return dates.get(next);
  }
}

public class X {
  private List<A> aList;
  public A getUpcoming() {
    return Util.getUpcoming(aList);
  }
}

What I'm really trying to do is just avoid writing getUpcoming(List<?> aList) for each class that has a list of IHasDate's.

Is there a better strategy for what I'm trying to do?

Right now I've been able to get around it by having a function that takes a list of IHasDate's and returns the index of the upcoming object in the list, but I have to create a new list of IHasDate's from aList first and it all just feels kind of clunky.

What I was hoping for was something along these lines.

public T getUpcoming(List<T implements IHasDate> dates) {
  //...
}

CodePudding user response:

You are sooo close.

  • Related