本文介绍了Java的字符数组 - 删除元素的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
在Java中,我想从一个字符数组删除某些元素,因此它确实是这样的:
In Java, I want to delete certain elements from a char array so it does something like:
char[] Array1 = {'h','m','l','e','l','l'};
Array1 = //character index[2] to character index[5]
如何才能做到这一点?
How can this be done?
推荐答案
在Java中,你不能删除一个数组元素。但是,你可以:
In Java you can't delete elements from an array. But you can either:
创建一个新的的char []
复制只有你想保留的元素;为此,你可以使用 System.arraycopy()
或更简单的 Arrays.copyOfRange()
。例如,对于只复制数组的前三个字母:
Create a new char[]
copying only the elements you want to keep; for this you could use System.arraycopy()
or even simplerArrays.copyOfRange()
. For example, for copying only the first three characters of an array:
char[] array1 = {'h','m','l','e','l','l'};
char[] array2 = Arrays.copyOfRange(array1, 0, 3);
或者使用列表与LT;性格>
,它可以让你获得一个子列表与一系列的元素:
Or use a List<Character>
, which allows you to obtain a sublist with a range of elements:
List<Character> list1 = Arrays.asList('h','m','l','e','l','l');
List<Character> list2 = list1.subList(0, 3);
这篇关于Java的字符数组 - 删除元素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!