首页 > 解决方案 > 有没有更简单的方法来移动数组中的对象,使它们相邻?

问题描述

我正在解决一个问题,它在一个大小为 7 的数组中给出一个对象数组(4 个对象),所以有 3 个空值。阵列被加扰。我需要合并元素,使它们以相同的顺序位于数组的 0、1、2、3 空间中。空值必须放在数组末尾的空间 4、5、6 上。这是我到目前为止所拥有的:

//a car object has a name and top speed

public void consolidate() {
    int numCars = 0;
    for (int i = 1; i < cars.length; i++) {
        if (cars[i] != null)
            numCars++;
    }
    for (int k = 0; k < numCars; k++) {
        for (int i = 1; i < cars.length; i++) {
            if (cars[i - 1] == null) {
                cars[i - 1] = cars[i];
                cars[i] = null;
            }
        }
    }
}

标签: javaarrays

解决方案


If you are okay with creating a separate array of the same length but null values at the end, you can do it very simply as shown below:

int j=0;
Car[] newCars = new Car[cars.length];
for(int i=0; i<cars.length; i++) {
    if(cars[i] != null) 
        newCars[j++] = cars[i];
}

推荐阅读