从数组中删除元素 [英] Delete element from array

查看:160
本文介绍了从数组中删除元素的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述


可能重复:

从数组中删除元素(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}

是否有快速的方法来摆脱这些元素等于0

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数组不能是调整大小。您需要创建一个新数组。

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.

您可以使用列表执行此操作。你最好的办法是创建一个整数列表;添加非零元素;然后使用toArray从列表中创建一个数组。

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.

这篇关于从数组中删除元素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆