Adding element at the middle of scala.collection.immutable.list in Java
I am using scala immutable list in Java. I want to add element at the middle of this list. Can someone h开发者_开发技巧elp me on this please? Thanks
Let sList
be a Scala List, let List
be the Scala List type and 42
the element to add:
final int half = sList.size /2;
final List<Int> first = sList.take(half);
final List<Int> second = sList.drop(half);
final List<Int> result = first.$colon$colon$colon( second.$colon$colon( 42 ) );
Vague answer to a vague question:
There are several ways to split an immutable list, e.g. using take
and drop
. From the parts (including your middle elements), you can assemble a new immutable List, e.g. using :::
, which should be called $colon$colon$colon
in Java, IIRC.
Please add some code if you need more details.
Hmmm… you are using an immutable list. The meaning of the word "immutable" is that it can not be changed - if there is a way to add an element to the middle of such a list, it would be a bug.
Edit: actually, there are probably ways to add elements in such a list - probably manipulating the corresponding data at the JVM level would do the trick - but that would still be bad, because every other program that uses an immutable list expects that list to always stay the same.
精彩评论