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

ArrayList零元素移至末尾且保留非零元素顺序的代码故障排查求助

Fixing Your ArrayList Zero-Moving Issue

Hey there! Let’s figure out why your code isn’t shifting those zeros to the end, and get it working right away.

First, What’s Wrong With Your Current Code?

Let’s go through the key issues step by step:

  • No actual list modifications: Your code just shuffles values around in local variables (hold and hold1) but never updates the original list. When you do hold1 = 0, you’re only changing the local variable, not the element in nums.
  • Unused variables: The last variable gets incremented but never used for anything meaningful—so it’s not helping move elements at all.
  • Logical gaps: Your loops don’t handle swapping or repositioning elements. You’re just checking for zeros and storing them in a variable, but not doing anything to move them to the end.

Working Solutions

Here are two solid approaches to solve this problem, both keeping non-zero elements in their original order while pushing zeros to the end.

Approach 1: Two-Pointer Technique (In-Place Modification)

This method is efficient (uses O(1) extra space) and modifies the list directly:

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

public class MoveZeros {
    public static void main(String[] args) {
        // Convert to ArrayList to ensure full modifiability (Arrays.asList has limitations)
        List<Integer> nums = new ArrayList<>(Arrays.asList(0, 1, 0, 3, 12));
        int nonZeroPos = 0;

        // First pass: Move all non-zero elements to the front
        for (int i = 0; i < nums.size(); i++) {
            if (nums.get(i) != 0) {
                nums.set(nonZeroPos, nums.get(i));
                nonZeroPos++;
            }
        }

        // Second pass: Fill the rest of the list with zeros
        for (int i = nonZeroPos; i < nums.size(); i++) {
            nums.set(i, 0);
        }

        System.out.println(nums); // Output: [1, 3, 12, 0, 0]
    }
}

How this works:

  • We use nonZeroPos to track where the next non-zero element should go. Every time we find a non-zero, we place it at nonZeroPos and move the pointer forward.
  • After collecting all non-zeros at the front, we just fill the remaining spots with zeros.

Approach 2: Collect Non-Zeros, Then Add Zeros (Simpler Logic)

If you don’t mind using a little extra space, this method is super straightforward:

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

public class MoveZeros {
    public static void main(String[] args) {
        List<Integer> nums = Arrays.asList(0, 1, 0, 3, 12);
        List<Integer> result = new ArrayList<>();

        // Gather all non-zero elements first
        for (Integer num : nums) {
            if (num != 0) {
                result.add(num);
            }
        }

        // Add the required number of zeros to the end
        int zeroCount = nums.size() - result.size();
        for (int i = 0; i < zeroCount; i++) {
            result.add(0);
        }

        System.out.println(result); // Output: [1, 3, 12, 0, 0]
    }
}

How this works:

  • We iterate through the original list and collect every non-zero element into a new list.
  • Then we calculate how many zeros we need (original list length minus non-zero count) and add them all to the end of the new list.

Quick Note About Arrays.asList()

The list returned by Arrays.asList() is a fixed-size wrapper around the original array. You can modify elements with set(), but you can’t add or remove elements (it’ll throw an UnsupportedOperationException). That’s why in Approach 1, we wrap it in an ArrayList for full flexibility.

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.04.30 22:37:47