本文介绍了在 Scala 中将元素附加到列表的末尾的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我无法将 T
类型的元素添加到列表 List[T]
中.我尝试使用 myList ::= myElement
但它似乎创建了一个奇怪的对象并且访问 myList.last
总是返回放在列表中的第一个元素.我该如何解决这个问题?
I can't add an element of type T
into a list List[T]
.I tried with myList ::= myElement
but it seems it creates a strange object and accessing to myList.last
always returns the first element that was put inside the list. How can I solve this problem?
推荐答案
List(1,2,3) :+ 4
Results in List[Int] = List(1, 2, 3, 4)
请注意,此操作的复杂度为 O(n).如果您经常需要此操作,或者对于长列表,请考虑使用其他数据类型(例如 ListBuffer).
Note that this operation has a complexity of O(n). If you need this operation frequently, or for long lists, consider using another data type (e.g. a ListBuffer).
这篇关于在 Scala 中将元素附加到列表的末尾的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!