3

I am trying to delete an object from an array of objects, however I cannot seem to get it too work. I'm new to java and noticed that you cannot simply do .remove() for an array. I know you can use an ArrayList, but is there a way of deleting an element from an array in java? I know you can't technically do that, because an array is a fixed length, so what I did was assign the value null to the object reference in the array. This works, however when I print my array I get this error.

Error

 java.lang.NullPointerException

Object def

public class Dog {
    //Iniatilising instance variables
    private String name;
    private String breed;
    private Gender gender;
    private int age;
    ...

Test Class Constants

public class TestDog {
//Create a constant value for MAX
static final int MAX = 10;
//Define a constant PROMPT
static final String PROMPT = "---->";
//Define a constant SPACES
static final String SPACES = "     ";
//String array of menu options
static final String options[] = {"Add new Dog","Display details for a Dog",
        "Update details for a Dog","List all Dogs","Delete all Dogs","Delete one Dog","Quit"};
//Define a constant QUIT
static final int QUIT = options.length;
//Create an array capable of managing up to MAX Dog instances
static Dog pets[] = new Dog[MAX];
static Dog empty[] = new Dog[MAX];
//Define a value 'count' to indicate number of objects in array
static int count = 0;
//A menu title
static String title = "Dog Manager";
//Define a menu using title & options
static Menu myMenu = new Menu(title,options);
//Define a Scanner
static Scanner input = new Scanner(System.in);

Test Class Delete Method

    public static void deleteOneDog() {
    System.out.println("\nOK - Delete one dog");
    boolean noDogs = false;
    if (count == 0) {
        System.out.println(PROMPT+"Sorry, there are no dogs.");
        noDogs = true;
        }
    else {
        System.out.println("We have the following Dogs:");
        for(int index=0; index<count;index++) {
            System.out.println(SPACES+(index+1)+". " + pets[index].getName());
            if (!noDogs) {
                System.out.println(PROMPT + "Enter selected dog name: ");
                String name = input.nextLine();
                for (int i = 0;i<count;i++) {
                    //Find dog and delete it
                    if (pets[i].getName().contentEquals(name)) {
                        pets[i] = null;
                    }
                }
            }
        }
    }
}
Lyra Orwell
  • 1,048
  • 4
  • 17
  • 46
  • Arrays are fixed size. You cannot remove an element. You can set an element to null, which is what you have done. But then you have a null element in your array. You could move all subsequent items down to fill in the gap. Then the null would be at the end if your array instead of in the middle. – khelwood Oct 12 '19 at 08:25
  • u can use arraList and override Dog equals method so u can easily remove and add to this list even print that – hossein rasekhi Oct 12 '19 at 08:27
  • No, you can't directly delete an element from an array. But you may stream it and use a filter to perform this. Please take a look at https://stackoverflow.com/questions/24112715/java-8-filter-array-using-lambda – Ed de Almeida Oct 12 '19 at 08:33
  • see `ArrayList`, Use a variable `size` to record the size of the array – meng Oct 12 '19 at 09:58

3 Answers3

3

In java when an array is initialized, it preserves the memory for that initialization which it needs to hold the data corresponding to the data type of the array declared.

So deleting an array element is something you can not do.

Simple thing that you can do is to shift the other array elements left by overriding the array element that need to be removed from array. Which means declaring new variable that holds the number of elements that the array is currently holding.

Then removing array element becomes simple as this.

  • shift elements to left starting from the element that you want to be removed.

  • decrement the variable by 1

    When you want to get the current array elements, you can simply loop through the array with reference to the no of elements variable.

Community
  • 1
  • 1
2

There is no direct way to remove elements from an Array in Java. Though Array in Java objects, it doesn't provide any methods to add(), remove() or search an element in Array. This is the reason Collection classes like ArrayList and HashSet are very popular.

Though

Thanks to Apache Commons Utils, You can use there ArrayUtils class to remove an element from array more easily than by doing it yourself. One thing to remember is that Arrays are fixed size in Java, once you create an array you can not change their size, which means removing or deleting an item doesn't reduce the size of the array. This is, in fact, the main difference between Array and ArrayList in Java.

What you need to do is create a new array and copy the remaining content of this array into a new array using System.arrayCopy() or any other means. In fact, all other API and functions you will use do this but then you don't need to reinvent the wheel.


    import java.util.Arrays;
    import org.apache.commons.lang.ArrayUtils;

     ....
    //let's create an array for demonstration purpose
    int[] test = new int[] { 101, 102, 103, 104, 105};

    System.out.println("Original Array : size : "
                           + test.length );
    System.out.println("Contents : " + Arrays.toString(test));

    // let's remove or delete an element from an Array
    // using Apache Commons ArrayUtils
    test = ArrayUtils.remove(test, 2); //removing element at index 2

    // Size of an array must be 1 less than the original array
    // after deleting an element
    System.out.println("Size of the array after
              removing an element  : " + test.length);
    System.out.println("Content of Array after
             removing an object : " + Arrays.toString(test));
Vikalp Patel
  • 10,669
  • 6
  • 61
  • 96
-1

in https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array, tells that you can delete a item by its index using array.splice(pos, n), where pos is the index where it starts deleting and n is the quantity of elements deleted.