Search code examples
javagenericscasting

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

Solution

  • 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!