0

I'm working on a project and this is one of the task: create a method called "remove()" which can remove an element from an array. After removing it, if the number of elements are less than 1/4 of the array, the size of the array needs to decrease by half.

For example: I have an size 100 array with 25 elements in it. After removing one element, I will have 24 elements, and the size of my array will be 50.

Here is my code:

    //First create a method decrese
    private decrease() {
        if (numElement < (1 / 4) * (Array.length)) {
        Array[] newarray = new Array[(Array.length) / 2];
        for (int i = 0; i < numElement; i++)
            newarray[i] = Array[i];
        Array = newarray;   
    }

    //Then create my Remove method
    public void remove(ToRemove){
    if (numElement > 0) {                //First check if my array is empty
        for (int i = 0; i < numElement; i++) {
            if (Array[i].equals(ToRemove)) {
                Array[i] = Array[numElement - 1];
                Array[numElement - 1] = null;
                numElement--;
                decrease();
            }
        } 
     //if the Array is empty, also decrease the size 
     decrease();
     }

After some test run, my remove works fine,the Array length would never decrese no matter what size I put in.

Can some one help me. Thanks

Qwert
  • 67
  • 6
  • 2
    Java arrays have a fixed length. You'll need to create a new (smaller) array. – Elliott Frisch Feb 03 '18 at 00:57
  • 1
    Possible duplicate of [Division of integers in Java](https://stackoverflow.com/questions/7220681/division-of-integers-in-java) – Tom Feb 03 '18 at 00:57
  • 3
    Further to Tom's comment: you expect (1/4=.25), but 1 and 4 are of type int, so 1/4 is actually 0. Since you are hardcoding the values, simply use 0.25 instead. If you were using variables, you would cast to double. – Ian Mc Feb 03 '18 at 01:14
  • @IanMc Thanks guys, I can't believe I was stuck in this for 3 hours – Qwert Feb 03 '18 at 01:31
  • 2
    Possible duplicate of [Resize an Array while keeping current elements in Java?](https://stackoverflow.com/questions/13197702/resize-an-array-while-keeping-current-elements-in-java) – glee8e Feb 03 '18 at 13:37

2 Answers2

1

Also, you should just use if (numLength < (Array.length / 4)) rather then (1/4) * (Array.length); Don't do any weird casting or something like that. By default, java integer division will floor the result if that's the behavior you expect.

Also, you should be able to just use some Arrays.copyOfRange and System.arraycopy to achieve your copying needs.

https://docs.oracle.com/javase/7/docs/api/java/lang/System.html https://docs.oracle.com/javase/7/docs/api/java/util/Arrays.html

Here's a simple code snippet that basically implement removing elements from arrays.

import java.lang.reflect.Array;
import java.util.Arrays;

public class MySpecialArray<T> {

T[] buf;

int size;

Class<T> type;

public MySpecialArray(Class<T> type, int initialBufSize) {
    this.size = 0;
    this.type = type;

    buf = (T[]) Array.newInstance(type, initialBufSize);
}

    /**
 * Like arraylist add, it will basically add freely until it reaches the max length of the buffer.
 * Then it has to expand the buffer. It uses buf.length * 2 + 1 to account for when an initialBufSize of 0 is
 * supplied.
 * @param elem
 */
public void add(T elem) {
    if (this.size == this.buf.length) {
        int newSize = this.buf.length * 2 + 1;
        buf = Arrays.copyOf(buf, newSize);
    }
    this.buf[this.size] = elem;
    this.size += 1;
}

public void add(T...elements) {
    for(T elem : elements) {
        this.add(elem);
    }
}

/**
 * Remove all occurrences of an element. Also reduce the max buf_size of the array if my utilized size is less than a fourth of my max buf size.
 * @param removeMe element to remove all occurrences of
 * @return
 */
public void remove(T removeMe) {
    boolean found = false;
    for(int i = 0; i < this.size; i++) {
        if (buf[i].equals(removeMe)) {
            System.arraycopy(buf, i+1, buf, i, this.size - i);
            this.size -= 1;
            if (this.size < this.buf.length / 4) {
                this.buf = Arrays.copyOf(buf, this.buf.length / 2);
            }
        }
    }
}

/**
 * Remove the last element
 * @return
 */
public T remove() {
    if (this.size == 0) {
        throw new RuntimeException("Cannot remove from empty buffer");
    }
    T removed = this.buf[this.size -1];
    this.size -= 1;
    if (this.size <= this.buf.length / 4) {
        int newSize = this.buf.length / 2;
        this.buf = Arrays.copyOf(this.buf, newSize);
    }

    return removed;
}

@Override
public String toString() {
    StringBuilder sb = new StringBuilder();
    for(int i = 0; i < this.size; i++) {
        sb.append(this.buf[i].toString()).append(",");
    }
    return sb.toString();
}

public static void main(String...args) {
    MySpecialArray<Integer> arr = new MySpecialArray(Integer.class, 50);
    arr.add(10, 2, 4, 3, 5, 11, 9, 3, 8, 16);

    System.out.println("===Pre removed===");
    System.out.println(arr.buf.length);
    System.out.println(arr.size);
    System.out.println(arr);
    arr.remove(3);

    System.out.println("===After removing 3===");
    System.out.println(arr.buf.length);
    System.out.println(arr.size);
    System.out.println(arr);
 }
}

This sample, when just running it, will print out

===Pre removed===
50
10
10,2,4,3,5,11,9,3,8,16,
===After removing 3===
25
8
10,2,4,5,11,9,8,16,
Benjamin Liu
  • 313
  • 1
  • 8
0

Simple answer is "You can not"

Java Array data structures are of fixed size and you can't change the size of Same Array Object "once it is created".

If you need to change size you either need to copy its contents to a new Array Object or use different data structure like ArrayList which does this internally.

Amit Mahajan
  • 895
  • 6
  • 34