5

I faced a problem where I needed to add a new value in the middle of an Array (i.e. make a copy of the original array and replace that with the new one). I successfully solved my problem, but I was wondering whether there were other methods to do this without changing the array to buffer for a while.

val original = Array(0, 1, 3, 4)
val parts = original.splitAt(2)
val modified = parts._1 ++ (2 +: parts._2)

res0: Array[Int] = Array(0, 1, 2, 3, 4)

What I don't like on my solution is the parts variable; I'd prefer not using an intermediate step like that. Is that the easiest way to add the value or is there some better ways to do add an element?

1
  • This is a nice solution for using a List. Commented Apr 18, 2016 at 13:48

4 Answers 4

11

This is precisely what patch does:

val original = Array(0, 1, 3, 4)
original.patch(2, Array(2), 0)      // Array[Int] = Array(0, 1, 2, 3, 4)
Sign up to request clarification or add additional context in comments.

Comments

1

You can use a mutable version of a collection to do this. The method insert do what you want (insert an element at a given index).

Comments

1

Well, if indeed the extra variable is what's troubling you, you can do it in one go:

val modified = original.take(2) ++ (2 +: original.drop(2))

But using a mutable collection like Augusto suggested might fit better, depending on your use case (e.g. performance, array size, multiple such edits...).

Comments

1

The question is, what's the context? If you are doing this in a loop, allocating a new array every time will kill your performance anyway, and you should rethink your approach (e.g. collect all the elements you want to insert before inserting them).

If you aren't, well, you can use System.arraycopy to avoid any intermediate conversions:

val original = Array(0, 1, 3, 4)
val index = 2
val valueToInsert = 2

val modified = Array.ofDim[Int](original.length + 1)
System.arraycopy(original, 0, modified, 0, index)
modified(index) = valueToInsert
System.arraycopy(original, index, modified, index + 1, original.length - index)

But note how easy it's to make an off-by-one error here (I think there isn't one, but I haven't tested it). So the only reason to do it is if you really need high performance, and that's only likely if it happens in a loop, in which case go back to the second sentence.

Comments

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.