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

Java技术需求:从ArrayList移除指定值及扩展IntegerList类功能

Got it, let's break down these two Java tasks step by step—super straightforward once you map out the logic!


1. Removing All Occurrences of a Value from an ArrayList

There are a few reliable ways to do this without running into common pitfalls like ConcurrentModificationException:

Method 1: Use Java 8+ removeIf() (Cleanest Approach)

This is the simplest way if you're on a modern Java version. The removeIf() method handles safe iteration and modification under the hood:

import java.util.ArrayList;

public class ArrayListRemoveExample {
    public static void main(String[] args) {
        ArrayList<Integer> numbers = new ArrayList<>();
        numbers.add(2);
        numbers.add(5);
        numbers.add(2);
        numbers.add(8);
        numbers.add(2);

        // Remove all instances of 2
        numbers.removeIf(n -> n == 2);

        System.out.println(numbers); // Output: [5, 8]
    }
}

Method 2: Use an Iterator (Compatible with Older Java Versions)

If you need to support pre-Java 8 code, an iterator is the safe way to modify the list while iterating:

import java.util.ArrayList;
import java.util.Iterator;

public class ArrayListRemoveExample {
    public static void main(String[] args) {
        ArrayList<Integer> numbers = new ArrayList<>();
        numbers.add(2);
        numbers.add(5);
        numbers.add(2);
        numbers.add(8);
        numbers.add(2);

        Iterator<Integer> iterator = numbers.iterator();
        while (iterator.hasNext()) {
            Integer num = iterator.next();
            if (num == 2) {
                iterator.remove(); // Safe removal that avoids exceptions
            }
        }

        System.out.println(numbers); // Output: [5, 8]
    }
}

What to Avoid

Don't use a for-each loop to remove elements—it will throw a ConcurrentModificationException because you're modifying the list while iterating over it:

// BAD CODE - WILL THROW EXCEPTION
for (Integer num : numbers) {
    if (num == 2) {
        numbers.remove(num);
    }
}

2. Implementing Required Features for IntegerList Class

Let's build out the IntegerList class with all the requested features. We'll start with the instance variables, then add the increaseSize() method, and finally the addElement() method.

Complete IntegerList.java Code

public class IntegerList {
    // Instance variables to track state
    private int[] elements;
    private int currentSize; // Tracks number of actual elements in the list
    private int capacity;    // Tracks total length of the underlying array

    // Default constructor: starts with capacity 10
    public IntegerList() {
        this.capacity = 10;
        this.elements = new int[capacity];
        this.currentSize = 0;
    }

    // Custom constructor for initial capacity
    public IntegerList(int initialCapacity) {
        if (initialCapacity <= 0) {
            throw new IllegalArgumentException("Initial capacity must be positive");
        }
        this.capacity = initialCapacity;
        this.elements = new int[capacity];
        this.currentSize = 0;
    }

    // increaseSize: doubles the array capacity (common expansion strategy)
    private void increaseSize() {
        this.capacity *= 2;
        // Create new array with expanded capacity
        int[] newElements = new int[capacity];
        // Copy existing elements to the new array
        System.arraycopy(this.elements, 0, newElements, 0, this.currentSize);
        // Replace old array with the expanded one
        this.elements = newElements;
    }

    // addElement: adds a new value to the end of the list
    public void addElement(int newVal) {
        // If array is full, expand it first
        if (currentSize == capacity) {
            increaseSize();
        }
        // Add the new value at the next available index, then increment size
        elements[currentSize] = newVal;
        currentSize++;
    }

    // Optional helper method to print the list (for testing)
    public void printList() {
        System.out.print("IntegerList: [");
        for (int i = 0; i < currentSize; i++) {
            System.out.print(elements[i]);
            if (i != currentSize - 1) {
                System.out.print(", ");
            }
        }
        System.out.println("]");
    }

    // Optional getters for testing/state access
    public int getCurrentSize() {
        return currentSize;
    }

    public int getCapacity() {
        return capacity;
    }

    // Test the class functionality
    public static void main(String[] args) {
        IntegerList list = new IntegerList(3);
        list.addElement(10);
        list.addElement(20);
        list.addElement(30);
        list.printList(); // Output: IntegerList: [10, 20, 30]
        System.out.println("Current Size: " + list.getCurrentSize()); // 3
        System.out.println("Capacity: " + list.getCapacity()); // 3

        // Adding a 4th element triggers increaseSize
        list.addElement(40);
        list.printList(); // Output: IntegerList: [10, 20, 30, 40]
        System.out.println("Current Size: " + list.getCurrentSize()); // 4
        System.out.println("Capacity: " + list.getCapacity()); // 6
    }
}

Key Details:

  • Instance Variables: currentSize keeps track of how many elements are actually stored, while capacity is the total length of the underlying array.
  • increaseSize(): Marked as private because it's an internal helper—callers don't need to trigger it manually (the addElement() method handles this automatically when the array is full).
  • addElement(): Checks if the array is at capacity before adding a new element, expands if needed, then places the new value and updates the size.

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.19 06:43:05