Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to convert ArrayList<subClass> to ArrayList<super> in java

Tags:

java

arraylist

I hava a method setData(ArrayList<super> list), so anyone who want set data can have their own entity, just need to extends from super class. but when they call setData, how they convert ArrayList to ArrayList?

Now i use setData(new ArrayList(list)), but it's not a good solution.

Anyone can tell me how to convert or another solution can avoid the problem. Very appreciated!

like image 510
dreamtale Avatar asked Mar 12 '12 04:03

dreamtale


People also ask

Can ArrayList store subclass objects?

As far as it's concerned, the ArrayList only holds references to SuperClass -type objects, and it can only call SuperClass 's methods on objects it retrieves from it.

What is the SuperClass of ArrayList?

When we examine the API (Application Programming Interface) of Java's ArrayList, we notice that ArrayList has the superclass AbstractList . AbstractList , in turn, has the class Object as its superclass. Each class can directly extend only one class.

Can you use binary search on an ArrayList?

binarysearch() works for objects Collections like ArrayList and LinkedList.


2 Answers

It depends on what you want to do with the list afterwards. If you're just going to read from it, you can declare your method like this:

setData(ArrayList<? extends SuperType> list)

You can't add anything to that list, though, because you won't know what ? is. Another option is to create a copy when calling your method:

List<SubType> subtypeList = ...;
setData(new ArrayList<SuperType>(subtypeList));
like image 50
vanza Avatar answered Oct 21 '22 11:10

vanza


Instead of coding

setData(new ArrayList(list));

you could simply use

setData((ArrayList<super>)((Object)list));

Casting list to Object first and then to ArrayList will force the compiler to accept the method invocation. As an added bonus, you don't suffer the performance expense of creating a new array list.

like image 31
skiller3 Avatar answered Oct 21 '22 09:10

skiller3