开发者

Delete element from array [duplicate]

This question already has answers here: Closed 11 years ago.

Possible Duplicate:

Removing an element from an Array (Java)

Is there a way I can get rid of some elements in an array. for instance, if i have this array

int testArray[] = {0,2,0,3,0,4,5,6}

Is there a "fast" way to get rid of the elements that equal 0

int resultArray[] = {2,3,4,5,6}

I tried this function but I got lost using Lists

public int[] getRidOfZero(int []s){
   List<> result=new ArrayList<>();
   for(int i=0; i<s.length; i++){
     if(s[i]<0){
       int temp = s[i];
       result.add(temp)开发者_开发百科;
     }
   }
   return result.toArray(new int[]);
}


Java arrays can't be resized. You need to create a new array.

Count the non-zero elements in the array. Create a new array that size. Copy the elements from the old to the new array, skipping over zero elements.

You can do this with lists. Your best bet is to create a list of Integers; add non-zero elements to it; then use toArray to create an array from the list.


You're quite close, but:

  • Your generics were messed up (List<> is syntactically invalid)
  • Your comparison was only adding the element if it was less than zero (rather than adding it if it was not equal to zero)
  • You were calling the wrong toArray() method.Because ints are primitives, you have to turn the list back into an array yourself.

public int[] getRidOfZero(int[] s) {
    List<Integer> result = new ArrayList<Integer> ();
    for (int i : s) {
        if (i != 0) {
            result.add(i);
        }
    }

    int[] toReturn = new int[result.size()];
    for (int i=0; i<result.size(); i++) {
        toReturn[i] = result.get(i);
    }

    return toReturn;
}


Since you're starting with an array, you'll need to create a new array and copy the items from the old array, excluding the zeros.

If you remove a bunch of zeros at once, this is going to be fast.

Otherwise, you'll need to begin with the doubly-linked LinkedList.

LinkedList has an iterator that allows you to move along the list and remove elements, which will be a constant-time operation.

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜