返回接口对象的列表

发布于 2024-11-05 06:32:36 字数 722 浏览 0 评论 0原文

我有一个类Category,它实现了CategoryManager 接口。接下来是维护ListCard

现在我想返回此列表,但类别为 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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

压抑⊿情绪 2024-11-12 06:32:36

这与 .NET 示例中的情况相同。您不应该在集合类型之间进行转换。它之所以有效,是因为 Java 的擦除。如果你没有收到演员的警告,我会有点惊讶。

最准确的选项是:

public List<? extends CategoryManager> getAllCategories()
{
    return categories;
}

负面的是 ListList不一样?扩展 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:

public List<? extends CategoryManager> getAllCategories()
{
    return categories;
}

The negative is that List<CategoryManager> is not the same as List<? extends CategoryManager>. However, it does match the suggested intent of the method name.

谈情不如逗狗 2024-11-12 06:32:36

不需要 位,这使得 getAllCategories 成为 通用方法。这会工作得很好:

public class Category implements CategoryManager
{   
    List<Category> categories = new ArrayList<Category>();

    public List<? extends CategoryManager> getAllCategories()
    {
        return categories;
    }
}

There's no need for the <T extends CategoryManager> bit, which makes getAllCategories a generic method. This will work just fine:

public class Category implements CategoryManager
{   
    List<Category> categories = new ArrayList<Category>();

    public List<? extends CategoryManager> getAllCategories()
    {
        return categories;
    }
}
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文