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?

Beto Caldas
  • 2,198
  • 2
  • 23
  • 23

2 Answers2

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))
guenhter
  • 11,255
  • 3
  • 35
  • 66
  • 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)) – Beto Caldas Jul 03 '17 at 06:19
  • I found this other solution: ChatAdapter(user.chats.map { it.value } as ArrayList) – Beto Caldas Jul 03 '17 at 06:21
  • 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. – guenhter Jul 03 '17 at 06:24
  • 2
    I wouldn't use user.chats.map { it.value } as ArrayList because this has much more runtime overhead than ArrayList(am.values) – guenhter Jul 03 '17 at 06:27
  • I changed it to your second solution. I found this post about what you say: https://stackoverflow.com/a/43116238/1593067 Is that your point? – Beto Caldas Jul 03 '17 at 06:30
  • 1
    Yes, this describes it quite well. – guenhter Jul 03 '17 at 06:33
  • Let us [continue this discussion in chat](http://chat.stackoverflow.com/rooms/148188/discussion-between-guenhter-and-beto-caldas). – guenhter Jul 03 '17 at 06:44
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 }
dedda1994
  • 151
  • 1
  • 15
  • I commented about this on checked solution. – Beto Caldas Jul 06 '17 at 20:55
  • 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. – dedda1994 Jul 07 '17 at 12:39