我想在循環中向一個Scala ListBuffer添加一些對象,但是每次添加一個對象時,它都會在循環的下一次迭代中消失。Scala - ListBuffer在每次添加循環後清空本身
當我之前並添加新條目後打印ListBuffer的內容,我得到下面的輸出:
加前:ListBuffer()
後添加:ListBuffer(com.me .FeatureV2 @ 20d953ba)
加前:ListBuffer()
後添加:ListBuffer([email protected])
加前:ListBuffer()
後添加:ListBuffer([email protected])
代碼:
def generateStatistics(df: DataFrame): List[FeatureV2] = {
var features = ListBuffer[FeatureV2]()
val dataColumn = "data"
for (field <- df.schema.fieldNames){
val columnType: String = df.select(field).dtypes(0)._2
if (columnType == StringType.toString){
val statsDf: DataFrame = getStats(df, field, dataColumn)
for (row <- statsDf){
println("Before add: " + features)
val feature = new FeatureV2()
feature.element = row.getString(0)
feature.count = row.getLong(1)
feature.sum = row.getDouble(2)
feature.max = row.getDouble(3)
feature.min = row.getDouble(4)
feature.feature = field
features += feature
println("After add: " + features)
}
}
}
features.toList
}
有時不過,我得到以下幾點:
加入前:ListBuffer()
後添加:ListBuffer([email protected])
加前:ListBuffer([email protected])
後添加:ListBuffer([email protected], COM .me.FeatureV2 @ 4b0df9e5)
加前:ListBuffer()
後添加:ListBuffer([email protected])
這看起來像它實際上是普惠在ListBuffer中,但它已被清除。與垃圾收集有關嗎?
你確定你只調用一次'generateStatistics''嗎? –
@JeanLogeart是的,絕對。 – karoma
在附註中,請使用ListBuffer作爲val並使用+ =([see here](http://docs.scala-lang.org/overviews/collections/concrete-mutable-collection-classes.html ))。這很奇怪,很難推理,因爲你正在修改對象引用。 – slouc