开发者

How do you remove the first instance of an element value in an array?

Add a method void removeFirst(int newVal) to the IntegerList class that removes the first occurrence of a value from the list. If the value does not appear in the list, it should do nothing (but it's not an error). Removing an item should not change the size of the array, but note that the array values do need to remain contiguous, so when you remove a value you will have to shift everything after it down to fill up its space. Also remember to decrement the variable that keeps track of the number of elements.

Please help, I have tried all of the other solutions listed on this site regarding "r开发者_Go百科emoving an element from an array" and none have worked.


This method supports the same functionality as Collection.remove() which is how an ArrayList removes the first matching element.

public boolean remove(int n) {
    for (int i = 0; i < size; i++) {
        if (array[i] != n) continue;
        size--;
        System.arraycopy(array, i + 1, array, i, size - i);
        return true;
    }
    return false;
}

Rather than write this code yourself, I suggest you look at Trove4J's TIntArrayList which is a wrapper for int[] You can also read the code for ArrayList to see how it is written.


You could do this:

 int count; //No of elements in the array
 for(i=0;i<count;i++) 
 {
     if(Array[i]==element )
     {
          swap(Array,i,count);
            if(count)
            --count;
            break;  
     } 


 }
 int  swap(int Array[],int i,int count)
 {
     int j;
       for(j=i;j<=count-i;j++)
       a[i]=a[i+1];

 }

This is not the Full Implementation.You have to create a class and do this.


Using the method below

public static <TypeOfObject> TypeOfObject[] removeFirst(TypeOfObject[] array, TypeOfObject valueToRemove) {
    TypeOfObject[] result = Arrays.copyOf(array, array.length - 1);
    List<TypeOfObject> tempList = new ArrayList<>();
    tempList.addAll(Arrays.asList(array));
    tempList.remove(valueToRemove);
    return tempList.toArray(result);
}

You can remove the first element of any array by calling the method as demonstrated in the below JUnit test.

@Test
public void removeFirstTest() {
    // Given
    Integer valToRemove = 5;
    Integer[] input = {1,2,3,valToRemove,4,valToRemove,6,7,8,9};
    Integer[] expected = {1,2,3,4,valToRemove,6,7,8,9};
    
    // When
    Integer[] actual = removeFirst(input, valToRemove);
    
    // Then
    Assert.assertArrayEquals(expected, actual);
}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜