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
So I have class
A that implements
B that implements
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
When the user selects one type, say
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
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
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);