3

I am using scala immutable list in Java. I want to add element at the middle of this list. Can someone help me on this please? Thanks

3 Answers 3

7

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 ) );
Sign up to request clarification or add additional context in comments.

Comments

2

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.

Comments

0

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.

2 Comments

yes, Immutable means that it cannot be changed but because it is immutable the add operation returns a new collection. I would like to know how that new collection can be generated?
You make a new list! The whole point of immutable lists is you make a new one every time it changes ! (not exactly due to link list tricks, but think of it like that)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.