如何删除从一个数组的元素? [英] How to delete elements from an array?

查看:115
本文介绍了如何删除从一个数组的元素?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我如何给定索引处删除整数,我怎么COM preSS myInts

这是我得到了什么,但我不断收到一个错误。

 公共无效deleteInt(INT指数){    INT [] = newInts Arrays.copyOf(myInts,myInts.length);    如果(myInts [指数]!= 0){
        myInts [索引] = 0;        对于(INT I:myInts){
            如果(myInts [I]!= 0){
                newInts [I] = myInts [I]
            }
        }
    }
    myInts = newInts;
    currentInt ++;
}

这是我的错误:


  

异常线程mainjava.lang.ArrayIndexOutOfBoundsException:11



解决方案

这code不使用增强的for循环正确的:

 的for(int我:myInts){
        如果(myInts [I]!= 0){
            newInts [I] = myInts [I]
        }
    }

它试图从myInts读取元素我,但我是一个元素的内容,而不是它的索引。因此,一旦某个元素包含一个值>数组的长度你的outofbounds例外。

 公共无效deleteInt(INT指数){    //可以是1元作为较短,我们将删除1个元素
    //还,复制原数组的内容是浪费时间
    //所以我们只是创造它。
    INT [] newInts =新INT [myInts.length-1];    //最简单的方法是使用一个额外的变量,以跟踪的插入
    //新数组
    INT J = 0;
    的for(int i = 0; I< myInts.length;我++){
        如果(我!=指数){
            newInts [J ++] = myInts [I]
        }
    }    //所以现在我们有数组的新副本缩短,但由于功能是无效的,
    //它的生命结束在这里:)
}

How do I delete the integer at the given index and how do I compress myInts?

This is what I got but I keep getting an error.

public void deleteInt(int index) {

    int[] newInts = Arrays.copyOf(myInts, myInts.length);

    if (myInts[index] != 0) {
        myInts[index] = 0;

        for (int i : myInts) {
            if (myInts[i] != 0) {
                newInts[i] = myInts[i];
            }
        }
    }
    myInts = newInts;
    currentInt++;
}

This is the error I get:

Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 11

解决方案

This code doesn't use the enhanced for loop properly:

    for (int i : myInts) {
        if (myInts[i] != 0) {
            newInts[i] = myInts[i];
        }
    }

It tries to read element i from myInts, but i is the content of an element, not its index. So, as soon as some element contains a value > array's length you the the outofbounds exception.

public void deleteInt(int index) {

    // can be 1 element shorter as we are going to erase 1 element
    // also, copying the contents of the original array in is a waste of time
    // so we just create it.
    int[] newInts = new int[myInts.length-1]; 

    // the easiest way is to use an extra variable to track the insertions in the
    // new array
    int j=0;
    for (int i=0; i < myInts.length; i++) {
        if (i != index) {
            newInts[j++] = myInts[i];
        }
    }

    // so now we have a new shortened copy of the array, but as the function is void,
    // its life ends here :)
}

这篇关于如何删除从一个数组的元素?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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