Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Method to return the same interface implementation as passed in

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.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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) {
  //...
}

>Solution :

You are sooo close. 🙂

public <T extends IHasDate> T getUpcoming(List<T> dates) {
//...
}
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading