简体   繁体   English

使用界面用对象填充列表

[英]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. 好的,所以我在JSF和Hibernate中有一个任务,我必须根据用户从网页从下拉菜单中选择的消息类型获取对象列表。

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 . 现在,用户可以选择的所有可能的对象类型(当我说对象时指的是Java类)都实现了一个接口,我们将其称为AbstractMessage

So I have class A that implements AbstractMessage , class B that implements AbstractMessage , C , D etc. 所以我有A实现AbstractMessageB ,一个实现AbstractMessageCD等的类B

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 . 现在,对我来说,选项是从下拉列表中为每种情况选择许多A,B,C,D等类型的列表,或者使用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. 当用户选择一种类型(例如A ,此AbstractMessage列表将成为类型A的列表。至少是这样的想法-只使用一个AbstractMessage类型的列表,而不是使用大量A B C等类型的列表。

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)? 如何使该列表成为“ A”,“ B”,“ C”类型的列表(取决于我已经拥有的if-else语句的结果)?

So everything is in place, but I don't know how can I convert the abstractList into an A , B , C type list? 一切就绪,但是我不知道如何将abstractList转换为ABC类型列表?

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: 或者,如果您只想从列表中获取AbstractMessage类型的对象:

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);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM