从数组删除项目和收缩阵列 [英] Delete item from array and shrink array

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

问题描述

我如何从一个数组中删除一个项目,然后调整数组的更小的尺寸?
同样的,我怎么能增加容量,如果我需要添加另一个项目?

How can I delete an item from an array, and then resize the array to the smaller size? Likewise, how can I increase the capacity if I need to add another item?

推荐答案

当你分配它,不能改变Java数组的大小是固定的。

The size of a Java array is fixed when you allocate it, and cannot be changed.


  • 如果你想成长或缩水现有阵列,您必须分配适当大小的新数组复制数组元素;例如使用 System.arraycopy(...) Arrays.copyOf(...)。副本循环的作品,以及,虽然显得有点笨重...海事组织。

  • If you want to "grow" or "shrink" an existing array, you have to allocate a new array of the appropriate size and copy the array elements; e.g. using System.arraycopy(...) or Arrays.copyOf(...). A copy loop works as well, though it looks a bit clunky ... IMO.

如果你想删除,从一个数组一个或多个项目(真正意义上的......不仅仅是替换它们),你需要分配一个新的小数组,并在要保留的元素复制。

If you want to "delete" an item or items from an array (in the true sense ... not just replacing them with null), you need to allocate a new smaller array and copy across the elements you want to retain.

有在第三方库(例如Apache下议院 ArrayUtils )的形式替代,但你可能要考虑是否有必要增加库依赖的只是的对,你可以用5-10线code的实现自己的方法的缘故。

There are alternatives in the form of 3rd-party libraries (e.g. Apache Commons ArrayUtils), but you may want to consider whether it is worth adding a library dependency just for the sake of a method that you could implement yourself with 5-10 lines of code.

这是更好(即简单......在许多情况下,更有效的 1 )使用列表类,而不是一个数组。这会照顾(至少)不断增长的后备存储的。并且有需要插入和列表中的任意位置删除元素的保健业务。

It is better (i.e. simpler ... and in many cases, more efficient1) to use a List class instead of an array. This will take care of (at least) growing the backing storage. And there are operations that take care of inserting and deleting elements anywhere in the list.

例如,的ArrayList 类使用数组作为后盾,并自动根据需要生长的数组。它不会自动降低支持数组的大小,但你可以告诉它要做到这一点使用 trimToSize()方法;例如。

For instance, the ArrayList class uses an array as backing, and automatically grows the array as required. It does not automatically reduce the size of the backing array, but you can tell it to do this using the trimToSize() method; e.g.

ArrayList l = ...
l.remove(21);
l.trimToSize();  // Only do this if you really have to.


1 - 我说的是在很多情况下更有效,因为的ArrayList 使用一个简单的双大小的策略时,它需要成长的后盾数组。这意味着,如果通过重复追加到其生长的列表中,每个元素将被平均一个额外的时间被复制。相反,如果你这样做有一个数组,你最终会接近复制每个数组元素为N平均/ 2次。


1 - I say it is "more efficient in many cases" because ArrayList uses a simple "double the size" strategy when it needs to grow the backing array. This means that if grow the list by repeatedly appending to it, each element will be copied on average one extra time. By contrast, if you did this with an array you would end up copying each array element close to N/2 times on average.

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

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