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.
相关问题
- Delete Messages from a Topic in Apache Kafka
- Is there a limit to how many levels you can nest i
- Jackson Deserialization not calling deserialize on
- How to maintain order of key-value in DataFrame sa
- How to toggle on Order in ReactJS
Arrays in Java have a fixed number of elements. But you can make that element null like this:
array[element]==null;
And that is the same as removing it from the array. You can also have a variable that keeps track of how many elements aren't null, so that you can even have an array.length kind of thing that follows that. that's what I do anyway.
Java arrays have a fixed length, so this cannot be done directly.
If you want to combine two arrays, look at this answer.
If you want to add to the array, you should use a
List
or anArrayList
instead.I misread your question and mixed up
splice
andslice
.The class
java.util.Arrays
provides some static functions useful when working with arrays. See the official documentation for other functions: http://docs.oracle.com/javase/8/docs/api/java/util/Arrays.html.Java's equivalent for
slice
is:Arrays.copyOfRange(array, from, to)
.A similar method to
splice
isaddAll
(http://docs.oracle.com/javase/8/docs/api/java/util/ArrayList.html#addAll-int-java.util.Collection-). But you need to use ajava.util.ArrayList
instead an array and it is not possible to remove elements with it. You would have to provide the elements as another collection, e.g. anArrayList
. So it is equivalent to callingsplice(index, 0, element1, element2, ...)
In standard Java libraries, there is no equivalent functionality.
There is
java.util.Arrays
class, but no similar functionality there.Here is a Java implementation of the
Array.prototype.splice()
method as per the JavaScript MDN specification.The following JUnit code tests this implementation:
Edit: As @denys-séguret pointed out correctly, this implementation differs from the JavaScript spec as it does not mutate/modify the original array. Instead, this implementation returns a new array instance.
Edit: This implementation is available with the following maven artifact, at the given maven repo:
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.