Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to cast ArrayList<> from List<>

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)); 
like image 701
Eugene Avatar asked Feb 27 '11 16:02

Eugene


People also ask

How do I cast an ArrayList to a list?

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

What does <> In an ArrayList represent?

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 .

What is a list <> in Java?

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.

Can you cast collection to ArrayList?

The ArrayList constructor is an effective way to get the contents of a Collection into a new ArrayList.


1 Answers

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!

like image 83
corsiKa Avatar answered Oct 07 '22 18:10

corsiKa