Reputation: 1579
I have a primitive type array from which I want to remove an element at the specified index. What is the correct and efficient way to do that?
I am looking to remove the element in the way mentioned below
long[] longArr = {9,8,7,6,5};
int index = 1;
List list = new ArrayList(Arrays.asList(longArr));
list.remove(index);
longArr = list.toArray(); // getting compiler error Object[] can't be converted to long[]
but the above approach looks to work with with Object only not with primitives.
Any alternative to that? I can not use any third party/additional libraries
Upvotes: 1
Views: 2731
Reputation: 928
Integer[] arr = new Integer[] {100,150,200,300};
List<Integer> filtered = Arrays.asList(arr).stream()
.filter(item -> item < 200)
.collect(Collectors.toList());
Upvotes: 0
Reputation: 719336
You need to create a new array and copy the elements; e.g. something like this:
public long[] removeElement(long[] in, int pos) {
if (pos < 0 || pos >= in.length) {
throw new ArrayIndexOutOfBoundsException(pos);
}
long[] res = new long[in.length - 1];
System.arraycopy(in, 0, res, 0, pos);
if (pos < in.length - 1) {
System.arraycopy(in, pos + 1, res, pos, in.length - pos - 1);
}
return res;
}
NB: the above has not been tested / debugged ....
You could also do the copying using for loops, but arraycopy
should be faster in this case.
The org.apache.commons.lang.ArrayUtils.remove(long[], int)
method most likely works like the above code. Using that method would be preferable ... if you were not required to avoid using 3rd-party open source libraries. (Kudos to @Srikanth Nakka for knowing / finding it.)
The reason that you can't use an list to do this is that lists require an element type that is a reference type.
Upvotes: 5
Reputation: 758
Use org.apache.commons.lang.ArrayUtils.
long[] longArr = {9,8,7,6,5};
int index = 1;
longArr=ArrayUtils.remove(longArr, index);
Upvotes: 0
Reputation: 3397
In addition to the answer by StephenC, have a look at https://www.cs.cmu.edu/~adamchik/15-121/lectures/Arrays/arrays.html.
It explains java arrays pretty well.
Upvotes: 0