Home > Net >  How to delete an item in the array and keeping the order the same?
How to delete an item in the array and keeping the order the same?

Time:10-08

I'm working on this project that allows me to add and delete elements In the array. When I delete elements in the array there would be a zero in that space and the code should shift the values after the deleted value to take its place. For Example: In the Array {1, 2, 3, 4, 5}. I choose to delete 3. My output should be {1, 2, 4, 5}. Instead my output is {1, 2, 5, 4}. Could someone help me figure out why it would do that? And how to rectify it?

import java.util.Scanner;
import java.util.Arrays;

public class IntBag2 {
    private static final int INITIAL_SIZE = 20;
    private static int[] bag;
    private int capacity;

    public IntBag2() {
        bag = new int[INITIAL_SIZE];
    }

    public IntBag2(int capacity) {
        bag = new int[capacity];
    }

    public boolean add(int item) {
        if (capacity == bag.length)
            return false;

        bag[capacity  ] = item;

        return true;
    }

    public boolean delete(int item) {
        for (int i = 0; i < capacity; i  ) {
            if (bag[i] == item) {
                bag[i] = bag[--capacity];
                return true;
            }
        }

        return false;
    }

    @Override
    public String toString() {
        String result = "Bag: ";
        for (int i = 0; i < capacity; i  )
            result  = bag[i]   " ";
        return result;
    }

    public static void main(String[] args) {
        Scanner input = new Scanner(System.in);
        IntBag2 intBag = new IntBag2();
        boolean done = false;

        while (!done) {
            System.out.println("1. Add an Item to the Array");
            System.out.println("2. Delete an item in the Array");
            System.out.println("3. toString");
            switch (input.nextInt()) {
            case 1:
                System.out.println("Add an Item to the Array");
                System.out.println(intBag.add(input.nextInt()));
                break;
            case 2:
                System.out.println("Delete Item of Array");
                System.out.println(intBag.delete(input.nextInt()));
                break;
            case 3:
                System.out.println("toString");
                System.out.println(intBag.toString());
                break;
            }
        }
        input.close();
    }

}

CodePudding user response:

A simpler implementation of delete is possible allowing to "delete" all entries in the array equal to the given item and shift the remaining ones to the front efficiently:

public boolean delete(int item) {
    System.out.println("deleting "   item); // for debug purposes
    int oldCapacity = capacity;
    for (int i = 0, j = 0; i < oldCapacity; i  ) {
        if (bag[i] != item) {
            bag[j  ] = bag[i];
        } else {
            capacity--;
        }
    }
    System.out.println("new capacity = "   capacity); // for debug

    // or use Arrays.fill(bag, capacity, oldCapacity, -1); instead of the loop
    for (int i = capacity; i < oldCapacity; i  ) {
        bag[i] = -1; // mark free entries with -1 in the tail
    }

    return oldCapacity == capacity;
}

Also, method toString should use StringBuilder if multiple concatenation are used in loop, or for brevity the following method print using utility methods from Arrays may be implemented:

public void print() {
    System.out.println(Arrays.toString(Arrays.copyOf(bag, capacity)));
}

Test:

IntBag ibag = new IntBag(10);
ibag.add(1);
ibag.add(3);
ibag.add(3);
ibag.add(2);
ibag.add(1);
ibag.print();
ibag.delete(2);
ibag.print();
ibag.delete(1);
ibag.print();

Output:

[1, 3, 3, 2, 1]
deleting 2
new capacity = 4
[1, 3, 3, 1]
deleting 1
new capacity = 2
[3, 3]

CodePudding user response:

With the line bag[i] = bag[--capacity]; you are basically getting the last item in your array and place it in the location of the deleted one.

Given that you are using int[] (instead of Integer[]) we can't assign an index of the array as null. The best we can do is assigning it -1 or create a new array.

I decided to create a new array from scratch. The following will do the trick.

public class IntBag2 {
    private static final int INITIAL_SIZE = 20;
    private static int[] bag;
    private int capacity;

    public IntBag2() {
        bag = new int[INITIAL_SIZE];
    }

    public IntBag2(int capacity) {
        bag = new int[capacity];
    }

    public boolean add(int item) {
        if (capacity == bag.length)
            return false;

        bag[capacity  ] = item;

        return true;
    }

    public boolean delete(int item) {
        int[] newBag = new int[capacity];
        int newCapacity = capacity;
        boolean deleted = false;
        for (int i = 0, j = 0; i < capacity; i  ) {
            if (bag[i] == item && !deleted) {
                deleted = true;
                newCapacity = capacity - 1;
            } else {
                newBag[j  ] = bag[i];
            }
        }

        bag = newBag;
        capacity = newCapacity;
        return deleted;
    }

    @Override
    public String toString() {
        String result = "Bag: ";
        for (int i = 0; i < capacity; i  )
            result  = bag[i]   " ";
        return result;
    }
}
  • Related