Are lists in Kotlin random access data structure a...
# getting-started
t
Are lists in Kotlin random access data structure and is it the same case for the list in Java? Also, how does one verify if the list in random-access collection or not practically through code sample?
r
List<T>
can't be said to be an random access structure There are several different implementations of this interface, notably
ArrayList<T>
(random access) and
LinkedList<T>
(NOT random access - `get(i)`/`[i]` are linear in time for linked list)
m
Kotlin provides the interface
RandomAccess
which you can use to check whether a list supports fast index based access.
e
(same as Java)
🙌 1
LinkedList is not random access, however there is very little reason to use it
m
I’ve always seen the use of LinkedList as a code smell for premature optimization 🙂
e
"listOf()", the return value of ".map{}", etc. return a random access list
so unless you're explicitly creating a linked list your list is almost certainly random access
n
agreed that LinkedList is a low-key code smell. it's useful for queue-type things where you're popping things off the front a lot, but often there are better alternatives (like ArrayDeque)