Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
145 views
in Technique[技术] by (71.8m points)

java - Function for changes a cell in a list

I have a list of User objects with the values ??name and date, which at position 0 have the values ??Kate and 15:37. What a function should look like, which, when called, will change the values ??in this cell (at position 0) to Peter and 15:15 Here is my code:

class Test {
 private var list = mutableListOf<User>()
 private var user: User? = null

 private fun addItem() {
       user = User("Kate","15:37")
       list.add(0, user!!)
}
}

at a certain place in the code, I call the addItem method and I have a cell with the values Kate and 15:37. After that, I want to call a function that will change the values ??in this cell ...


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

Do you just want to change the item at position 0 in the list?

list[0] = User("Peter", "15:15")

If you want to replace the item with one that's a copy, but with certain changes:

list[0] = list[0].copy(name="Peter")

If you want to keep the same object at position 0, but change its state:

// note the use of var, so the properties are mutable
data class User(var name: String, var date: String)

// "get item 0, if it's not null, set these things on it",
// this is just a neat and concise way to do it
list[0]?.run {
    name = "Peter"
    date = "15:15"
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

Just Browsing Browsing

2.1m questions

2.1m answers

60 comments

57.0k users

...