Can somebody please explain me why I can't cast List<>
to ArrayList<>
with first approach and I do with second one? Thank you.
First approach:
ArrayList<Task> tmp = ((ArrayList<Task>)mTrackytAdapter.getAllTasks(token));
Second approach:
ArrayList<Task> tmp = new ArrayList<Task>(mTrackytAdapter.getAllTasks(token));
List<String> listofOptions = (List<String>) Arrays. asList(options); then you can user constructoru of an arraylist to instantiate with predefined values. ArrayList<String> arrlistofOptions = new ArrayList<String>(list);
It simply means that the ArrayList is of the type ? (ie: the type that the ArrayList describes or wraps is of type ?) which means that it can be any non-primitive type, as mentioned below. If you had an ArrayList<?> , it could contain a Long , a String , and even a Map .
In Java, a list interface is an ordered collection of objects in which duplicate values can be stored. Since a List preserves the insertion order, it allows positional access and insertion of elements. List interface is implemented by the following classes: ArrayList. LinkedList.
The ArrayList constructor is an effective way to get the contents of a Collection into a new ArrayList.
When you do the second one, you're making a new arraylist, you're not trying to pretend the other list is an arraylist.
I mean, what if the original list is implemented as a linkedlist, or some custom list? You won't know. The second approach is preferred if you really need to make an arraylist from the result. But you can just leave it as a list, that's one of the best advantages of using Interfaces!
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