How can I add element in specified index and if th...
# getting-started
s
How can I add element in specified index and if the index exist element, replace it.
Copy code
val list = mutableListOf<String>()

list.add(0, "a")
list.add(0, "b")

list.toString() // except [b], actual [b, a]
g
use list[0] = “b”
it’s the same as list.set(0, “b”)
s
How about the
a
? If call list[0] = “a” will cause exception
Is there a convenient way for each insert without check the list
g
What is your use case? I’m just not quite sure what if you real life example for this
If you just need a function which does ” add element in specified index and if the index exist element, replace it.“, there is no such function in stdlib, it’s probably better just to create own extension for this
🙆‍♂️ 1
Still curious about your use case for this
s
I need to show the list data according to its index and the user can add data into the list. first, the list is empty. User can only inset to 0 index then, user can choose to insert data to the end or selected the data that insert early and replace its value.
g
But insert is not replace
or selected the data that insert early and replace its value.
I think no need to overthink this, it’s just easy to check if there is item and set it
s
ok ty 😀
I was affect by the SQL
The INSERT OR REPLACE Statement.
g
Problem that there is no built-in transaction on list unlike database, checking for “contains” is a separate operation from add/set, so it cannot be done in a safe way under the hood of the list, only for thread safe list implementations, which are not used by default, because of performance penalty
🙆‍♂️ 1