在 Java 中删除元素后缩短数组长度

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/2777762/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-13 12:45:10  来源:igfitidea点击:

Shorten array length once element is remove in Java

javaarrays

提问by lupin

Note: Following is my homework/assignment, feel free not to answer if you will.

注意:以下是我的家庭作业/作业,如果你愿意,请不要回答。

I want to delete/remove an element from an String array(Set) basic, I'm not allowed to use Collections..etc.

我想从基本的字符串数组(Set)中删除/删除一个元素,我不允许使用 Collections..etc。

Now I have this:

现在我有这个:

void remove(String newValue) {

            for ( int i = 0; i < setElements.length; i++) {
               if ( setElements[i] == newValue ) {
                    setElements[i] = "";

               }
            }

       }   

I does what I want as it remove the element from an array but it doesn't shorten the length. The following is the output, basically it remove the element indexed #1.

我做我想做的,因为它从数组中删除元素,但它不会缩短长度。以下是输出,基本上它删除了索引为 #1 的元素。

D:\javaprojects>java SetsDemo
Enter string element to be added
A
You entered A
Set size is: 5
Member elements on index: 0 A
Member elements on index: 1 b
Member elements on index: 2 hello
Member elements on index: 3 world
Member elements on index: 4 six
Set size is: 5
Member elements on index: 0 A
Member elements on index: 1
Member elements on index: 2 hello
Member elements on index: 3 world
Member elements on index: 4 six

回答by BalusC

Basically you need to create a new array which is as long as the old array's length minus 1 and then you need to copy the valid elements from the old to the new array in a loop and then replace the old array with the new array.

基本上,您需要创建一个新数组,该数组的长度与旧数组的长度减 1 一样长,然后您需要在循环中将有效元素从旧数组复制到新数组,然后用新数组替换旧数组。

Since this is homework, details are left away. Feel free to post a comment for a bit more clarification.

既然如此homework,细节就不说了。随意发表评论以获得更多说明。

回答by zs2020

void remove(String newValue) {
    if(setElements.length == 0) return;
    String [] array = new String[setElements.length-1];
    int j = 0;
    for ( int i = 0; i < setElements.length; i++) {
       if ( setElements[i] != newValue ) {
            array[j++] = setElements[i];
       }
    }
    setElements = array;
}

回答by Jonathan M Davis

All that setElements[i] = "";does is change the value of an element in the array. It does not actually remove anything from the array. If you were using a collection class and called remove(i)on it, then you would actually be removing that element from the collection. But here, you're just changing its value. However, arrays in Java have a fixed size and cannot be resized, so there is no way to remove elements from them. The solution, therefore, is to create a new array with a length one shorter than the old one, and then copy all of the values that you want to keep into the new one. So,

所有这些setElements[i] = "";作用是改变数组中的一个元素的值。它实际上并没有从数组中删除任何内容。如果您正在使用一个集合类并调用remove(i)它,那么您实际上将从集合中删除该元素。但在这里,你只是在改变它的价值。但是,Java 中的数组大小固定且无法调整大小,因此无法从中删除元素。因此,解决方案是创建一个长度比旧数组短一的新数组,然后将所有要保留的值复制到新数组中。所以,

  1. Create new array with a length of setElements.length - 1.

  2. Copy all of the elements in setElementsinto the new array, except for the one which you're looking to remove. Be careful of the fact that the indices into the two arrays will be off by one rather than equal once you've reached the index for the element that you wish to remove.

  3. Set setElementsto the new array if you want to keep using the same variable for your array.

  1. 创建长度为 的新数组setElements.length - 1

  2. 将所有元素复制setElements到新数组中,除了要删除的元素。请注意,一旦到达要删除的元素的索引,两个数组的索引将相差 1 而不是相等。

  3. setElements如果您想继续为数组使用相同的变量,请设置为新数组。

回答by Jonathan M Davis

The size of an array in Javacan't be changed once the array is created. The following links should help you with transferring the existing items to a new array :-)

Java 中数组的大小一旦创建就无法更改。以下链接应该可以帮助您将现有项目转移到新阵列:-)

See: System.arraycopyand Array.copyOf(*).

请参阅:System.arraycopyArray.copyOf(*)

回答by polygenelubricants

You can't change the length of an array object once it's created. Here's an excerpt from JLS 10.2. Array Variables:

一旦创建了数组对象,就不能更改它的长度。这是JLS 10.2的摘录数组变量

Once an array object is created, its length never changes. To make an array variable refer to an array of different length, a reference to a different array must be assigned to the variable.

一旦创建了一个数组对象,它的长度就永远不会改变。要使数组变量引用不同长度的数组,必须为变量分配对不同数组的引用。

This means that for this problem, you'd have to allocate a new array that's one-element shorter than the original array, and copy over the remaining elements.

这意味着对于这个问题,您必须分配一个比原始数组短一个元素的新数组,并复制其余元素。

If you need to remove element at index k, and the original array has Lelements, then you need to copy over elements (upper bounds are exclusive):

如果需要删除 index 处的元素k,并且原始数组有L元素,则需要复制元素(上限是独占的):

  • From [0,k)to [0,k)(kelements)
  • From [k+1,L)to [k,L-1)(L-k-1elements).
  • For a total of L-1elements copied
  • [0,k)[0,k)k元素)
  • [k+1,L)[k,L-1)L-k-1元素)。
  • 对于L-1复制的元素总数


static String[] removeAt(int k, String[] arr) {
    final int L = arr.length;
    String[] ret = new String[L - 1];
    System.arraycopy(arr, 0, ret, 0, k);
    System.arraycopy(arr, k + 1, ret, k, L - k - 1);
    return ret;
}
static void print(String[] arr) {
    System.out.println(Arrays.toString(arr));       
}   
public static void main(String[] args) {
    String[] arr = { "a", "b", "c", "d", "e" };
    print(arr); // prints "[a, b, c, d, e]"

    arr = removeAt(0, arr);
    print(arr); // prints "[b, c, d, e]"

    arr = removeAt(3, arr);
    print(arr); // prints "[b, c, d]"

    arr = removeAt(1, arr);
    print(arr); // prints "[b, d]"

    arr = removeAt(0, arr);
    arr = removeAt(0, arr);
    print(arr); // prints "[]"
}

This uses System.arraycopy; you can always write your own if this isn't allowed.

这使用System.arraycopy; 如果不允许,您可以随时编写自己的。

static void arraycopy(String[] src, int from, String[] dst, int to, int L) {
    for (int i = 0; i < L; i++) {
        dst[to + i] = src[from + i];
    }
}

This is a simplistic implementation that doesn't handle src == dst, but it's sufficient in this case.

这是一个不处理 的简单实现src == dst,但在这种情况下就足够了。

See also

也可以看看



Note on ==for Stringcomparison

注意上==String比较

Most of the time, using ==to compare Stringobjects is a mistake. You should use equalsinstead.

大多数时候,使用==比较String对象是错误的。你应该equals改用。

String ha1 = new String("ha");
String ha2 = new String("ha");
System.out.println(ha1 == ha2); // prints "false"
System.out.println(ha1.equals(ha2)); // prints "true"

See also

也可以看看