在Java中从数组中删除特定索引

3

我可以通过指定索引值从数组中删除特定元素吗?例如,我可以通过给出索引值1来删除字符d吗?

char[] words = { 'c', 'd', 'f', 'h', 'j' };

1
你说的“remove”是什么意思? - Sotirios Delimanolis
1
再次强调,“删除字符”是什么意思? - Sotirios Delimanolis
2
这是关于数组的官方教程。第一句话就有你的答案。 - Sotirios Delimanolis
1
使用ArrayList及其.remove()方法。数组是不可变的,因此您无法“删除”它,而是创建一个长度为-1的新数组,然后从源中填充它。 - Mark W
是的,谢谢你 @brso05... - GES Vadamanappakkam
显示剩余4条评论
6个回答

1
如果您需要从数组中删除一个或多个元素,而不将其转换为List或创建其他数组,则可以在O(n)的时间内执行此操作,而不依赖于要删除的项目数。
在这里,a是初始数组,int... r是要删除的元素的不同有序索引(位置):
public int removeItems(Object[] a, int... r) {
    int shift = 0;                             
    for (int i = 0; i < a.length; i++) {       
        if (shift < r.length && i == r[shift])  // i-th item needs to be removed
            shift++;                            // increment `shift`
        else 
            a[i - shift] = a[i];                // move i-th item `shift` positions left
    }
    for (int i = a.length - shift; i < a.length; i++)
        a[i] = null;                            // replace remaining items by nulls

    return a.length - shift;                    // return new "length"
}  

小测试:

Character[] words = {'c','d','f','h','j'};
removeItems(words, 1);
System.out.println(Arrays.asList(words));       // [c, f, h, j, null]

1
假设您不希望数组包含null值,那么您需要创建一个方法来实现。类似以下的代码应该就可以:
public char[] remove(int index, char[] arr) {
    char[] newArr = new char[arr.length - 1];
    if(index < 0 || index > arr.length) {
        return arr;
    }
    int j = 0;
    for(int i = 0; i < arr.length; i++) {
        if(i == index) {
            i++;
        }
        newArr[j++] = arr[i];
    }

    return newArr;
}

然后,只需用remove()的结果替换旧数组。

如果索引是最后一个元素,它会抛出ArrayIndexOutOfBoundsException异常。 因此,应该使用continue而不是i++。 - Eugene Kartoyev

1
如果您不想使用ArrayList,arraycopy是一个替代方法:
    System.arraycopy(words, 0, result, 0, i);
    System.arraycopy(words, i+1, result, i, result.length-i);

其中i是您要删除的索引。

希望能帮到您。

编辑: 当然,您应该最初定义正确的数组长度:

char[] result = new char[words.length-1];

顺便提一下,我/你应该将其命名为_char[] word_或_char[] letters_。另外,你的定义是错误的,应该是:char[] word = {'c','d','f','h','j'}; - lenhuy2106

0
 import java.util.Arrays;
  public class Main
 {
 public static void main(String[] args) {
 int[] my_array = {25, 14, 56, 15, 36, 56, 77, 18, 29, 49};

 int removeIndex = 1;
 int j=0;
  for(int i = 0; i < my_array.length -1; i++)
  {

    if(i==1)
    {

    }
    else
     {
        my_array[j] = my_array[i];
        j++;
     }

    }
     System.out.println("Original Array : "+Arrays.toString(my_array));   
    }
  }

0

你不能从数组中删除元素并“减小”数组大小。一旦创建了一个数组,它的长度就是固定的。

你可以将值更改为没有意义或被视为“空”的内容,但你无法删除它。
另一个选项是使用列表,例如ArrayList。它有一个“remove”方法,允许你实际上从中删除元素。


0
使用String类:
char[] words = { 'c', 'd', 'f', 'h', 'j' };
String str = new String(words);
words = (str.substring(0, Math.min(1, words.length)) + str.substring(Math.min(1 + 1, words.length))).toCharArray();

在jshell中运行:

jshell> char[] words = { 'c', 'd', 'f', 'h', 'j' };
words ==> char[5] { 'c', 'd', 'f', 'h', 'j' }

jshell> String str = new String(words);
str ==> "cdfhj"

jshell> words = (str.substring(0, Math.min(1, words.length)) + str.substring(Math.min(1 + 1, words.length))).toCharArray();
words ==> char[4] { 'c', 'f', 'h', 'j' }

jshell>

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接