You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Java自定义DynamicArray类求助:禁用ArrayList,部分方法待完成

Fixing & Completing Your DynamicArray Implementation

Hey there! Let's work through your DynamicArray assignment step by step. First, we'll fix the gaps in your existing code, then build out every required method to meet your assignment's specs.


Issues in Your Current Code

Let's start with the problems in the code you've already written:

  • Parameterized Constructor: You forgot to initialize the array field and set size to 0. Right now, even with a valid capacity, your array stays uninitialized.
  • Copy Constructor: Your current constructor accepts an int[] instead of a DynamicArray object (as required). You also need to handle null inputs by throwing an IllegalArgumentException.

Corrected Existing Constructors

Here's the fixed version of your initial code:

/**
 * @author Lisa Hergert
 */
public class DynamicArray {
    private int[] array;
    private int size;

    /*
     * Parameterized Constructor
     * @param capacity - initial capacity of the array
     * throws IllegalArgumentException if capacity is less than 0
     */
    public DynamicArray(int capacity) {
        if (capacity < 0) {
            throw new IllegalArgumentException("Size cannot be less than 0.");
        }
        this.array = new int[capacity];
        this.size = 0;
    }

    /*
     * No-arg Constructor - defaults to capacity 10
     */
    public DynamicArray() {
        this.array = new int[10];
        this.size = 0;
    }

    /*
     * Copy Constructor
     * @param other - the DynamicArray to copy
     * throws IllegalArgumentException if other is null
     */
    public DynamicArray(DynamicArray other) {
        if (other == null) {
            throw new IllegalArgumentException("Cannot copy a null DynamicArray.");
        }
        // Copy capacity and all occupied elements from the input array
        this.array = new int[other.array.length];
        this.size = other.size;
        for (int i = 0; i < other.size; i++) {
            this.array[i] = other.array[i];
        }
    }

Implementing Remaining Required Methods

Now let's tackle each missing method, with explanations for how they work:

1. int getSize()

Straightforward—just return the private size field:

public int getSize() {
    return this.size;
}

2. int[] toArray()

We need to return a new array containing only the elements that are actually in use (not the full capacity), so we create a new array of size this.size and copy elements over:

public int[] toArray() {
    int[] result = new int[this.size];
    for (int i = 0; i < this.size; i++) {
        result[i] = this.array[i];
    }
    return result;
}

3. public void push(int num)

Adds an element to the end. If the array is full, we double its capacity first:

public void push(int num) {
    // Check if array is at max capacity
    if (this.size == this.array.length) {
        // Handle edge case where initial capacity was 0
        int newCapacity = this.array.length == 0 ? 1 : this.array.length * 2;
        int[] newArray = new int[newCapacity];
        // Copy existing elements to the new array
        for (int i = 0; i < this.size; i++) {
            newArray[i] = this.array[i];
        }
        this.array = newArray;
    }
    // Add the new element and increment size
    this.array[this.size] = num;
    this.size++;
}

4. public int pop()

Removes and returns the last element. If the array is empty, we throw the required exception. We also shrink the array if capacity is 4x the current size:

public int pop() {
    if (this.size == 0) {
        throw new RuntimeException("Array is empty");
    }
    // Get the last element before decrementing size
    int lastElement = this.array[this.size - 1];
    this.size--;

    // Shrink array if capacity is 4x larger than current size
    if (this.array.length >= 4 * this.size && this.size > 0) {
        int newCapacity = this.array.length / 2;
        int[] newArray = new int[newCapacity];
        for (int i = 0; i < this.size; i++) {
            newArray[i] = this.array[i];
        }
        this.array = newArray;
    }
    return lastElement;
}

5. int get(int index)

Returns the element at the given index. Throws an exception if the index is invalid:

public int get(int index) {
    if (index < 0 || index >= this.size) {
        throw new IndexOutOfBoundsException("Illegal index");
    }
    return this.array[index];
}

6. int indexOf(int key)

Searches for the first occurrence of key and returns its index. Returns -1 if not found:

public int indexOf(int key) {
    for (int i = 0; i < this.size; i++) {
        if (this.array[i] == key) {
            return i;
        }
    }
    return -1;
}

7. void add(int index, int num)

Inserts an element at the specified index. Shifts elements to the right if needed, and expands the array if it's full:

public void add(int index, int num) {
    // Validate index: can be from 0 to size (adding at the end is allowed)
    if (index < 0 || index > this.size) {
        throw new IndexOutOfBoundsException("Illegal index");
    }
    // Expand array if full
    if (this.size == this.array.length) {
        int newCapacity = this.array.length == 0 ? 1 : this.array.length * 2;
        int[] newArray = new int[newCapacity];
        for (int i = 0; i < this.size; i++) {
            newArray[i] = this.array[i];
        }
        this.array = newArray;
    }
    // Shift elements from index onwards to the right by 1
    for (int i = this.size; i > index; i--) {
        this.array[i] = this.array[i - 1];
    }
    // Insert the new element
    this.array[index] = num;
    this.size++;
}

8. int remove(int index)

Removes the element at the specified index, shifts elements left, and shrinks the array if capacity is 4x the current size:

public int remove(int index) {
    if (index < 0 || index >= this.size) {
        throw new IndexOutOfBoundsException("Illegal index");
    }
    int removedElement = this.array[index];
    // Shift elements from index+1 onwards to the left by 1
    for (int i = index; i < this.size - 1; i++) {
        this.array[i] = this.array[i + 1];
    }
    this.size--;

    // Shrink array if capacity is 4x larger than current size
    if (this.array.length >= 4 * this.size && this.size > 0) {
        int newCapacity = this.array.length / 2;
        int[] newArray = new int[newCapacity];
        for (int i = 0; i < this.size; i++) {
            newArray[i] = this.array[i];
        }
        this.array = newArray;
    }
    return removedElement;
}

Key Notes

  • All edge cases are covered: empty arrays, null inputs, invalid indices, and even the rare case where initial capacity is 0.
  • The resize logic (double when full, halve when capacity is 4x size) follows your assignment's requirements exactly.
  • We never expose the private array field directly—all returns are new copies to maintain encapsulation.

内容的提问来源于stack exchange,提问作者Lisa

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.29 09:02:53