如何从数组中删除元素?

时间:2014-03-20 01:54:28

标签: java arrays

如何删除给定索引处的整数以及如何压缩myInts

这是我得到的,但我一直收到错误。

public void deleteInt(int index) {

    int[] newInts = Arrays.copyOf(myInts, myInts.length);

    if (myInts[index] != 0) {
        myInts[index] = 0;

        for (int i : myInts) {
            if (myInts[i] != 0) {
                newInts[i] = myInts[i];
            }
        }
    }
    myInts = newInts;
    currentInt++;
}

这是我得到的错误:

  

线程中的异常" main" java.lang.ArrayIndexOutOfBoundsException:11

3 个答案:

答案 0 :(得分:2)

为此你应该使用像ArrayList这样的东西。使用Array会让您像在您的exaple中一样制作代码,从质量和性能的角度来看,这通常是一个非常糟糕的主意。

编辑:请参阅以下代码:

ArrayList<int> ret = new ArrayList<int>(Arrays.asList(myInts));
ret.remove(index);
return ret.toArray();

答案 1 :(得分:2)

所以,首先进行单元测试:

package com.example;

import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.InjectMocks;
import org.mockito.runners.MockitoJUnitRunner;

import java.util.Arrays;

import static org.junit.Assert.assertTrue;

@RunWith(MockitoJUnitRunner.class)
public class ArrayExample_UT {

    @InjectMocks
    private ArrayExample subject;

    int[] testArray = {1, 2, 3, 4, 5};
    int[] expectedArray = {1, 2, 4, 5};

    @Test
    public void testThat_RemoveEntry_RemovesCorrectEntry() throws Exception {
        assertTrue(Arrays.equals(expectedArray, subject.removeEntry(2, testArray)));
    }
}

然后,一些运行绿色的代码:

package com.example;

class ArrayExample {

    public int[] removeEntry(int skipIndex, int[] sourceArray){
        int[] newArray = new int[sourceArray.length - 1];
        int targetIndex = 0;
        for(int i = 0; i < sourceArray.length; i++){
            if(i != skipIndex){
                newArray[targetIndex++] = sourceArray[i];
            }
        }
        return newArray;
    }
}

答案 2 :(得分:0)

此代码未正确使用增强型for循环:

    for (int i : myInts) {
        if (myInts[i] != 0) {
            newInts[i] = myInts[i];
        }
    }

它试图从myInts读取元素i,但我是元素的内容,而不是它的索引。因此,只要某个元素包含值&gt;数组的长度是你的outofbounds异常。

public void deleteInt(int index) {

    // can be 1 element shorter as we are going to erase 1 element
    // also, copying the contents of the original array in is a waste of time
    // so we just create it.
    int[] newInts = new int[myInts.length-1]; 

    // the easiest way is to use an extra variable to track the insertions in the
    // new array
    int j=0;
    for (int i=0; i < myInts.length; i++) {
        if (i != index) {
            newInts[j++] = myInts[i];
        }
    }

    // so now we have a new shortened copy of the array, but as the function is void,
    // its life ends here :)
}