kotlinarraylist

Kotlin - Convert Collection to Array List


I'm converting a Java application to Kotlin. In one area it's using apache IO's FileUtils listFiles functions.

These return collections and I'm having problems converting/casting the collections into ArrayList

        val myFiles = FileUtils.listFiles(mediaStorageDir, extensions, true) as ArrayList<File>

Whilst this compiles I get a runtime error as follows:

java.util.LinkedList cannot be cast to java.util.ArrayList

What's the correct way to convert a collection object into an ArrayList?


Solution

  • ArrayList is a class with implementation details. FileUtils is returning a LinkedList and that is why you are having issues. You should do a cast to List<File> instead since it is an interface that both ArrayList and LinkedList implement.

    If you would need to modify the returned list you can use MutableList<File> instead the immutable one.

    But this is not the best approach because if the creators of FileUtils later change the implementation details of their collections your code may start crashing.

    A better soulition if explicitly need it to be an arrayList instead of a generic list could be:

    val myFiles = FileUtils.listFiles(mediaStorageDir, extensions, true)
    val array = arrayListOf<File>()
    array.addAll(myFiles)