什么是从一个数组中删除第一个元素的最佳方式? [英] What is the best way to remove the first element from an array?
问题描述
我有字符串数组(的String []
),我需要删除的第一个项目。我如何能做到有效?
I have string array (String[]
) and I need to remove the first item. How can I do that efficiently?
推荐答案
在Java数组的大小不能改变。因此,技术上无法删除从数组中的元素。
The size of arrays in Java cannot be changed. So, technically you cannot remove any elements from the array.
,以模拟从数组移除元素的一种方式是创建一个新的,更小的阵列,然后将所有从原数组的元素复制到新的,更小的阵列
One way to simulate removing an element from the array is to create a new, smaller array, and then copy all of the elements from the original array into the new, smaller array.
String[] yourArray = Arrays.copyOfRange(oldArr, 1, oldArr.length);
然而,我不会建议上述方法。你真的应该使用列表与LT;弦乐>
。列出允许你从任何索引中添加和删除项目。这将类似于以下内容:
However, I would not suggest the above method. You should really be using a List<String>
. Lists allow you to add and remove items from any index. That would look similar to the following:
List<String> list = new ArrayList<String>(); // or LinkedList<String>();
list.add("Stuff");
// add lots of stuff
list.remove(0); // removes the first item
这篇关于什么是从一个数组中删除第一个元素的最佳方式?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!