返回接口对象的列表
我有一个类Category
,它实现了CategoryManager
接口。接下来是维护List
的Card
。
现在我想返回此列表,但类别为 CategoryManager
,因此为 List
。我这样做的原因是 Category
的“公共界面”非常丑陋,我想通过仅向外部用户显示干净的 CategoryManager
来缩小范围。代码>.
我该怎么做?
我想出了以下方法:
public <T extends CategoryManager> List<T> getAllCategories() {
return (List<T>) categories; //with categories beeing List<Category>
}
它确实有效,但我发现它相当难看,因为我在这里转换并返回 List
,从而丢失信息并且......好吧,我想你会同意,由于各种原因,它并不漂亮。
有人能提出更好/更好的解决方案吗?
问候 :-)
I have a class Category
that implements the interface CategoryManager
. Next there is Card
that maintains a List<Category>
.
Now I would like to return this list, but with categories as CategoryManager
, hence List<CategoryManager>
. The reason I'm doing this is that the "public interface" of Category
is extremly ugly, and I'd like to narrow it down by showing the outside user only the clean CategoryManager
.
How do I do this?
I've come up with the following method:
public <T extends CategoryManager> List<T> getAllCategories() {
return (List<T>) categories; //with categories beeing List<Category>
}
It does work,but I find it rather ugly, bacause I'm casting to and returning List<T>
here, thus losing information and... Well, I think you'll sgree that it's not pretty for various reasons.
Can anyone come with a better/nicer solution?
Regards :-)
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
这与 .NET 示例中的情况相同。您不应该在集合类型之间进行转换。它之所以有效,是因为 Java 的擦除。如果你没有收到演员的警告,我会有点惊讶。
最准确的选项是:
负面的是
List
与List
不一样?扩展 CategoryManager>
。但是,它确实符合方法名称的建议意图。The same point holds as holds in the .NET example. You should not cast between collection types. It works because of Java's erasure. I would be a little surprised if you were not getting a warning from the cast though.
The most accurate option is:
The negative is that
List<CategoryManager>
is not the same asList<? extends CategoryManager>
. However, it does match the suggested intent of the method name.不需要
位,这使得getAllCategories
成为 通用方法。这会工作得很好:There's no need for the
<T extends CategoryManager>
bit, which makesgetAllCategories
a generic method. This will work just fine: