0

I have an ArrayMap and I want a list of Chat to create and recyclerview.

val chats : ArrayMap<String,Chat>? = ArrayMap()

RecyclerView.Adapter

class ChatAdapter(var chats : ArrayList<Chat>){
   .
   .
   .
}

I get this ArrayMap from firebase. What is the best way to get an ArrayList?

2 Answers 2

2

You shouldn't use ArrayList in the public constructor (because then you make youself depending on exactly that implementation). Should be the MutableList interface:

class ChatAdapter(var chats : MutableList<Chat>){

I guess the ArrayMap is a usual Map (because I don't know that class). You can just write

val chats : ArrayMap<String,Chat>? = ArrayMap()
// ... initialize the chat
val adapter = ChatAdapter(am.values.toMutableList())

If you really need the ArrayList class for some reason, you can write

val adapter = ChatAdapter(ArrayList(am.values))
Sign up to request clarification or add additional context in comments.

7 Comments

I can't understande this "You shouldn't use ArrayList in the public constructor (because then you make youself depending on exactly that implementation).", but your second solution works: val adapter = ChatAdapter(ArrayList(am.values))
I found this other solution: ChatAdapter(user.chats.map { it.value } as ArrayList<Chat>)
ArrayList is an implementation, MutableList an interface. If possible, always use the interface e.g. in your case use the interface in the constructor. Because then you can pass ANY implementation (as ArrayList) to your ChatAdapter. Else you can just pass an ArrayList.
I wouldn't use user.chats.map { it.value } as ArrayList<Chat> because this has much more runtime overhead than ArrayList(am.values)
Yes, this describes it quite well.
|
0

If you don't need an ArrayList explicitly, you can use the ArrayMap.map() function like this:

val chats : ArrayMap<String,Chat>? = ArrayMap()
val list : List<Chat> = chats.map { it.value }

2 Comments

I commented about this on checked solution.
Thanks. I already thought it might be more expensive at runtime but wasn't sure so i thought it might not hurt to see another possible way. At least it's not completely wrong i guess.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.