Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do you delete an element from an array without creating a new array or using ArrayLists? java

Tags:

java

arrays

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;
                    }
                }
            }
        }
    }
}
like image 403
Lyra Orwell Avatar asked Oct 23 '25 07:10

Lyra Orwell


1 Answers

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.

like image 136
Hasintha Abeykoon Avatar answered Oct 25 '25 20:10

Hasintha Abeykoon