简体   繁体   English

从ListBuffer中删除元素

[英]Removing elements from ListBuffer

According to this posting , it is said that ListBuffer allows constant-time removal of the first and last elements. 根据这篇文章 ,据说ListBuffer允许恒定时间移除第一个和最后一个元素。 I've been looking into the API reference and the ListBuffer source code, but I can't find how I remove the last element in constant time while remove(0) will do the job for the first element. 我一直在研究API参考和ListBuffer源代码,但是我找不到如何在恒定时间内remove(0)最后一个元素的方法,而remove(0)会完成第一个元素的工作。 What would be the proper way to remove the last element? 删除最后一个元素的正确方法是什么?

Another question: is it possible to remove an element efficiently while iterating over a ListBuffer? 另一个问题:是否有可能在迭代ListBuffer时有效地删除元素? In Java it can be done with Iterator.remove() but the Scala iterator doesn't seem to have the remove() method... 在Java中,可以使用Iterator.remove()完成此操作,但是Scala迭代器似乎没有remove()方法...

The first question has an easy if disappointing answer: you can't remove the last element in constant time, as doing so would require a reference to the element-before-last. 第一个问题有一个令人失望的简单答案:您不能在固定时间内删除最后一个元素,因为这样做需要引用element-before-last。 (It's a singly linked list, inside a wrapper class that holds the beginning and end elements of the list.) (这是一个单链接列表,位于包装器类中,该包装器类包含列表的开始和结束元素。)

The second question is equally easy and perhaps disappointing: Iterator s in Scala are simply views of the collection. 第二个问题同样容易,甚至可能令人失望:Scala中的Iterator只是集合的视图。 They don't modify the underlying collection. 他们不修改基础集合。 (This is in keeping with the "immutable by default, mutable only when necessary" philosophy.) (这符合“默认情况下不可变,仅在必要时可变”的哲学。)

您可以使用trimEnd(1)删除最后一个元素

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM