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

Lyra Orwell :

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;
                    }
                }
            }
        }
    }
}
Vikalp Patel :

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

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=306242&siteId=1