Java eqivalent method of "splice(a,b,...)" in JavaScript method

Ernestas Gruodis picture Ernestas Gruodis · Mar 14, 2015 · Viewed 25.1k times · Source

someArray.splice(a,b,...) method in JavaScript adds or removes items to/from array. What could be good and simple solution to implement such method in Java language? Assume we have String[] array.

Answer

Denys Séguret picture Denys Séguret · Mar 14, 2015

Java arrays have a fixed length, so there's no such method.

You could imagine writing a utility function similar to splice in Java but it would return a different array. There's no point in having arrays in java if you resize them: it's not efficient and you can't share the instance.

The usual and clean solution is to use a List, which is a resizeable collection. ArrayList, the most commonly used List implementation is backed by an array but is efficient as the array isn't changed every time you resize the collection.