Casting Kotlin ArrayLists ClassCastException

Multi tool use
Casting Kotlin ArrayLists ClassCastException
I have a MutableList<Card>
called cards
that I am sorting based on one of the properties, using the sortedWith
function. This returns a sorted generic list type, so a cast is necessary. However, when I cast the list, it crashes with a ClassCastException:
MutableList<Card>
cards
sortedWith
private var cards: MutableList<Card> = ArrayList()
...
cards = cards.sortedWith(compareBy{it.face}) as ArrayList<Card>
java.lang.ClassCastException: java.util.Arrays$ArrayList cannot be cast to java.util.ArrayList
EDIT: I just realized I need to use the more generic type of cards for the cast, MutableList<Card>
. Now, can someone explain why the cast with ArrayList fails?
MutableList<Card>
2 Answers
2
The cast fails because the list returned by sortedWith
function is not an instance of java.util.ArrayList
.
sortedWith
java.util.ArrayList
Moreover it's unsafe to cast it to MutableList
too, because the implementation of sortedWith
can be changed later, so that it returns List
that's no longer a MutableList
.
MutableList
sortedWith
List
MutableList
If you have a MutableList
and you want to sort it, you have two options:
MutableList
either sort it in-place with the sortWith
function (not sortedWith
):
sortWith
sortedWith
cards.sortWith(compareBy{it.face})
// now cards list is sorted
or sort it to a new list and then copy it to a mutable list, if you need to mutate it after
cards = cards.sortedWith(compareBy{it.face}).toMutableList()
@GusW
sortBy { }
is a shortcut for sortWith(compareBy { })
. Better to ask as a separate question, and you'll get a more detailed answer.– Ilya
Jul 3 at 0:55
sortBy { }
sortWith(compareBy { })
There are easier ways to sort a list in place without creating a new one and assign back to the original. The simplest is cards.sortBy { it.face }
cards.sortBy { it.face }
By clicking "Post Your Answer", you acknowledge that you have read our updated terms of service, privacy policy and cookie policy, and that your continued use of the website is subject to these policies.
Thanks, sorting it in place is a much better option. What is the difference between sorting in place with sortWith and sortBy?
– Gus W
Jul 2 at 23:45