从java中的数组中删除特定索引 [英] Remove specific index from array in java

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

问题描述

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

Can I remove a specific element from array by mentioning index value? For example can I remove the character d by giving index value 1?

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

推荐答案

如果您需要从数组中删除一个或多个元素而不将其转换为 List 或创建额外的数组,您可以在O(n) 不依赖于要移除的项目数.

If you need to remove one or multiple elements from array without converting it to List nor creating additional array, you may do it in O(n) not dependent on count of items to remove.

这里,a 是初始数组,int... r 是要删除的元素的不同有序索引(位置):

Here, a is initial array, int... r are distinct ordered indices (positions) of elements to remove:

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]

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

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