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;
}
}
}
}
}
}