[英]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.我真正想做的是避免为每个具有 IHasDate 列表的类编写
getUpcoming(List<?> aList)
。
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.现在我已经能够通过一个函数来绕过它,该函数接受 IHasDate 的列表并返回列表中即将到来的对象的索引,但我必须首先从 aList 创建一个新的 IHasDate 列表,这一切都只是感觉有点笨重。
What I was hoping for was something along these lines.我所希望的是这些方面的东西。
public T getUpcoming(List<T implements IHasDate> dates) {
//...
}
You are sooo close.你太近了。
public <T extends IHasDate> T getUpcoming(List<T> dates) {
//...
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.