Search code examples
javaarrayslistarraylistinteger

removing an element from an array using ArrayList(java)


I am trying to remove an element from an array using ArrayList. however I cannot seem to get it to work. I'm new to java. Here is the code what i do

package workspace;
import java.util.*;
import java.util.stream.*;
public class Worksapce{
    private static Collection<Integer> returnarrayList;
    static int[] arrayRemover(int[] myArray,int index) {
        List<Integer>arrayList = IntStream.of(myArray) .boxed().collect(Collectors.toList()); 
        arrayList.remove(2); 
        returnarrayList = null;
        return returnarrayList.stream().mapToInt(Integer::intValue).toArray(); 
    }
public static void main(String[] args)  { 
    int myArray[]= {1,2,3,4};
    int index=2;
    myArray=arrayRemover(myArray,index);
    System.out.println(Arrays.toString(myArray));
}
}

Here is the error showing

enter image description here

I want to remove an element from the array.I know there is'nt a direct method in java to remove an element from the array.But there are exist several indirect methods.There I'm trying to remove element using arraylist. I didnt get the result. What are the mistakes in it? What i need to change?


Solution

  • You have the line returnarrayList = null;, then you attempt to invoke a method on null at the next line. I would just create a new array of myArray.length - 1 (because you're removing one element); then copy from 0 to index and then from index + 1 to the new array. Like,

    static int[] arrayRemover(int[] myArray, int index) {
        if (myArray == null || myArray.length < 2) {
            return myArray;
        }
        int[] r = new int[myArray.length - 1];
        System.arraycopy(myArray, 0, r, 0, index);
        System.arraycopy(myArray, index + 1, r, index, myArray.length - index - 1);
        return r;
    }