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!
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.
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.
binarysearch() works for objects Collections like ArrayList and LinkedList.
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));
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With