return a list of interfaced objects
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>开发者_JS百科;
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 :-)
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.
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;
}
}
精彩评论