Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/java/353.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Java 如何从数组中删除元素_Java_Arrays - Fatal编程技术网

Java 如何从数组中删除元素

Java 如何从数组中删除元素,java,arrays,Java,Arrays,我有一个数组,例如: String [][] test = {{"a","1"}, {"b","1"}, {"c","1"}}; 有人能告诉我如何从数组中删除元素吗。例如,我想删除项“b”,使数组看起来像: {{"a","1"}, {"c","1"}} 我找不到做这件事的方法。到目前为止,我在这里发现的东西对我不起作用:(没有从常规Java数组中“删除”项的内置方法 您要使用的是。您可以将数组中的项设置为nul

我有一个数组,例如:

String [][] test = {{"a","1"},
                    {"b","1"},
                    {"c","1"}};
有人能告诉我如何从数组中删除元素吗。例如,我想删除项“b”,使数组看起来像:

{{"a","1"},
 {"c","1"}}

我找不到做这件事的方法。到目前为止,我在这里发现的东西对我不起作用:(

没有从常规Java数组中“删除”项的内置方法


您要使用的是。

您可以将数组中的项设置为
null
test[0][1]=null;
)。但是,如果不重新创建数组,则无法“删除”该项以使数组比以前少一个元素。如果您计划定期更改数据结构中的数据,请单击
ArrayList
(或另一个集合类,具体取决于您的需要)可能更方便。

您不能从数组中删除元素。Java数组的大小是在分配数组时确定的,并且不能更改。您最好:

  • null
    分配到相关位置的数组;例如

    test[1] = null;
    
    这就给您留下了处理数组中
    null
    值所在的“洞”的问题。(在某些情况下,这不是问题……但在大多数情况下是。)

  • 在删除元素的情况下创建一个新数组;例如

    String[][] tmp = new String[test.length - 1][];
    int j = 0;
    for (int i = 0; i < test.length; i++) {
        if (i != indexOfItemToRemove) {
            tmp[j++] = test[i];
        }
    }
    test = tmp;
    
    String[]tmp=新字符串[test.length-1][];
    int j=0;
    对于(int i=0;i
    ApacheCommons
    ArrayUtils
    类有一些静态方法可以更灵活地完成这项工作(例如,但事实是这种方法创建了一个新的数组对象)

更好的方法是使用合适的
集合
类型。例如,
数组列表
类型有一种方法,允许您在给定位置删除元素。

我的解决方案是:


您不能从数组中删除元素=>这是正确的,但我们可以做一些事情来更改当前数组

No need assign null to the array at the relevant position; e.g.

test[1] = null;

Create a new array with the element removed; e.g.

String[][] temp = new String[test.length - 1][];
需要在字符串/数组处获取索引才能删除:IndexToRemove

for (int i = 0; i < test.length-1; i++) {
                if (i<IndexToRemove){
                    temp[i]=test[i];
                }else if (i==IndexToRemove){
                    temp[i]=test[i+1];
                }else {
                    temp[i]=test[i+1];
                }
}
test = temp;
for(int i=0;i如果(i)您最好使用
ArrayList
而不是数组