当前位置: 动力学知识库 > 问答 > 编程问答 >

java - Populate a list with objects using an interface

问题描述:

OK so I have a task in JSF and Hibernate where I have to obtain a list of objects depending on the type of message that the user selects from the web page, from a dropdown menu.

Now, all the possible kinds of objects (when I say objects I mean java classes) that the user can select all implement an interface, let's call it AbstractMessage.

So I have class A that implements AbstractMessage, class B that implements AbstractMessage, C, D etc.

Now the option for me is, to have many lists of type A, B, C, D etc for each case selected from the dropdown, or use one list of type AbstractMessage.

When the user selects one type, say A, this AbstractMessage list becomes a list of type A. At least, that's the idea - to just use one list of type AbstractMessage instead of a ton of lists of type A B C etc.

The question is - how can I do that? I already declared my abstract list as follows:

private List<AbstractMessage> abstractList = new ArrayList<AbstractMessage>();

How can I make this list become a list of type "A", "B", "C" (depending on the results of an if-else statement, that I already have)?

So everything is in place, but I don't know how can I convert the abstractList into an A, B, C type list?

I tried just declaring the list without initializing it, I tried casting, but it doesn't work. There has to be some very simple explanation for this. Thanks.

网友答案:

You could use a bounded wildcard:

List<? extends AbstractMessage> list;
...
list = new ArrayList<A>();
...
AbstractMessage var1 = list.get(0);
A var2 = (A) list.get(0);

List<A> list2 = (List<A>) list;
list2.add(new A());
A var3 = list2.get(0);

Or in the case you only want to get objects of type AbstractMessage from the list:

List<AbstractMessage> abstractList = new ArrayList<>();
...
abstractList.add(new A());
AbstractMessage var1 = abstractList.get(0);
A var2 = abstractList.get(0); // <-- Compiler error
A var3 = (A) abstractList.get(0);
...
List<A> list2 = new ArrayList<>();
...
abstractList.addAll(list2);
分享给朋友:
您可能感兴趣的文章:
随机阅读: