https://kotlinlang.org logo
Title
t

thhh

04/07/2021, 2:03 PM
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

Roukanken

04/07/2021, 3:01 PM
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

Michael Böiers

04/07/2021, 3:38 PM
Kotlin provides the interface
RandomAccess
which you can use to check whether a list supports fast index based access.
e

ephemient

04/07/2021, 3:50 PM
(same as Java)
🙌 1
LinkedList is not random access, however there is very little reason to use it
m

Michael Böiers

04/07/2021, 3:52 PM
I’ve always seen the use of LinkedList as a code smell for premature optimization 🙂
e

ephemient

04/07/2021, 3:52 PM
"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

nanodeath

04/07/2021, 3:58 PM
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)