3 回答

TA貢獻2003條經驗 獲得超2個贊
temp_storage.take(1)
這將返回修改后的List
. 它不會修改List
您調用它的位置。您忽略了返回值。
temp_storage.dropLast(1)
同樣的——你忽略了該函數正在做的工作。
println("FInal size: "+ temp_storage.size) //still size 2. Why not 1!?
它的大小相同,因為您沒有對它進行任何修改。
實現這一目標的方法是什么?
如果我明白你想要什么,請使用:
fun padding(tokenizedinput : ArrayList<ArrayList<Double>>) = arrayListOf(tokenizedinput[0])
在這里,我們:
獲取 tokenizedinput 的第一個元素
將其包含在 中
ArrayList
,因為您想要ArrayList<ArrayList<Double>>
回復

TA貢獻1795條經驗 獲得超7個贊
List.take(n)
或者List.dropLast(n)
將return
使用該操作創建一個新列表。它不會修改現有列表。嘗試以這種方式記錄或打印:-
println(temp_storage.take(1).size) // would be 1 println(temp_storage.dropLast(1).size) // would be 1
上面的輸出將是
1
,當且僅當列表的大小是2
要轉換為現有列表,請使用:-
temp_storage = ArrayList(temp_storage.dropLast(1)) // need to cast it to ArrayList<T> before assigning

TA貢獻1839條經驗 獲得超15個贊
要添加其他答案已經說過的內容,請從包含此方法的實際類中添加:
采取方法:
/**
* Returns a list containing first [n] elements.
*
* @throws IllegalArgumentException if [n] is negative.
*
* @sample samples.collections.Collections.Transformations.take
*/
public fun <T> Iterable<T>.take(n: Int): List<T> {
require(n >= 0) { "Requested element count $n is less than zero." }
if (n == 0) return emptyList()
if (this is Collection<T>) {
if (n >= size) return toList()
if (n == 1) return listOf(first())
}
var count = 0
val list = ArrayList<T>(n)
for (item in this) {
if (count++ == n)
break
list.add(item)
}
return list.optimizeReadOnlyList()
}
還有dropLast:
/**
* Returns a list containing all elements except last [n] elements.
*
* @throws IllegalArgumentException if [n] is negative.
*
* @sample samples.collections.Collections.Transformations.drop
*/
public fun <T> List<T>.dropLast(n: Int): List<T> {
require(n >= 0) { "Requested element count $n is less than zero." }
return take((size - n).coerceAtLeast(0))
}
可以在以下位置找到:_Collections.kt
這意味著它返回一個列表,它不會修改原始集合
添加回答
舉報