java:针对接口进行编程,但必须实例化一个具体类
我正在使用泛型进行第一步,我刚刚编写了一个泛型函数来比较两个 List 对象,就像这样
public static <T> List<T> diffAdded(List<T> source, List<T> dest) {
List<T> ret = new ArrayList<T>();
for(T element: dest) {
if (!source.contains(element)) {
ret.add(element);
}
}
return ret;
}
一切正常,但我正在实例化 ArrayList,因为显然我无法实例化接口 List
事实是我想返回一个与源类型相同的对象...
你如何处理这种情况?
我现在的方法会遇到任何演员问题吗?
多谢
I'm giving my first steps with generics, and I've just coded a generic function to compare two List objects, like this
public static <T> List<T> diffAdded(List<T> source, List<T> dest) {
List<T> ret = new ArrayList<T>();
for(T element: dest) {
if (!source.contains(element)) {
ret.add(element);
}
}
return ret;
}
Everything works fine, but I'm instantiating an ArrayList, because obviously I cannot instantiate an interface List
the fact is that I want to return an object of the same type as source...
how do you handle these kind of situations?
can I face any cast trouble with the method as it is right now?
thanks a lot
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
这个问题的答案几乎总是“返回与源类型相同的对象”实际上与您的应用程序无关,并且您处理问题的方式是错误的。
如果您的调用者需要特定的
List
实现,因为他们将对其执行特定类型的操作,那么他们可以自己进行复制...但是如果您的方法采用任意类型的参数List
,并且输出根据输入的确切实现在语义上发生变化,那么这是一个巨大的代码味道。让您的代码保持原样,如果您的方法的调用者确实需要特定的实现,那么他们可以将您的输出复制到该实现中。
The answer to this question is almost always that "returning an object of the same type as the source" is not actually relevant to your application, and that you're going about things the wrong way.
If your caller needs a specific
List
implementation, because they'll be doing a specific kind of operation on it, then they can do the copying themselves...but if your method takes an arbitrary argument of typeList
, and the output changes semantically depending on the exact implementation of the input, then that's a huge code smell.Leave your code as it is, and if your method's callers really, really need a specific implementation, then they can copy your output into that implementation themselves.
这里你有两个选择。
1:认识到接受。
List
接口作为输入类型意味着您明确表示您不关心底层实现。此外,通过返回List
它表明您的调用者也不应该关心底层实现。在大多数情况下,List
就是一个List
,细节并不重要。如果是这样,您应该显式返回 ArrayList2:进行一系列与您想要支持的
List
实现类型相匹配的多态调用。我非常认为第一个答案是你应该努力的方向。
You've got two choices here.
1: Realize that the point of accepting the
List<T>
interface as your input type means that you are explicitly saying that you don't care about the underlying implementation. Furthermore, by returning aList<T>
it says that your caller shouldn't care about the underlying implementation either. In most cases, aList
is aList
and the details shouldn't matter. If it does, you should explicitly returnArrayList<T>
instead.2: Make a bunch of polymorphic calls that match every
List
implementation type that you want to support.I very much think that the first answer is where you should direct your efforts.