Home > Blockchain >  ArrayBuffer copy all fields of this to another ArrayBuffer for first N entries
ArrayBuffer copy all fields of this to another ArrayBuffer for first N entries

Time:08-15

This works:

import scala.collection.mutable.ArrayBuffer
case class Z (a1:String, b1:String, ts1: Integer)

var d = new ArrayBuffer[Z]()  // empty buffer is created
d = ArrayBuffer(Z("Mark", "Hamlin", 2), Z("Kumar", "XYZ", 3), Z("Tom", "Poolsoft", 4)) 

//val g = d1.map(x => (x.a1, x.b1, x.ts1)) 
var Z1 = new ArrayBuffer[Z]()
for (x <- d) {
  Z1  = Z(x.a1, x.b1, x.ts1) 
}
println(Z1) 

How can I clone an entry of Z in the loop without having to specify all the field name of case class Z? Z(x.a1, x.b1, x.ts1) Cannot see that. There is a reason why I want to do it individually.

copyToArray and clone seem no go here. I would be happy if I could use a size as well, but am interested in the prime question.

I looked at this scala ArrayBuffer remove all elements with a predicat ,but I have no filter I can use. I need, say, first N to be copied.

CodePudding user response:

Answering "How can I clone an entry of Z in the loop without having to specify all the field name of case class Z?":

If you really want to create a new instance of each Z, you could do:

for (x <- d) {
  Z1  = x.copy()
}

But: most certainly, you do not need to do that. The Z-objects in your ArrayBuffer are immutable, so there is no reason to copy them (no one can modify them...). Instead, you could just add the same instances to your copied buffer:

for (x <- d) {
  Z1  = x
}

Since each x is immutable, there should not be a difference (but the second option saves the garbage collector some work because less objects get allocated).

  • Related