简体   繁体   English

从数组中删除最后一个元素

[英]Deleting the last element from an array

I am trying to delete an element from an array depending on the method's argument. 我试图根据方法的参数从数组中删除一个元素。 If the argument is the last element's position, I can't use the for loop and end up specifying an if statement just to satisfy that. 如果参数是最后一个元素的位置,则不能使用for循环并最终指定if语句来满足该要求。 Also trying to return the current name in that position after the deletion. 删除后还要尝试返回该位置的当前名称。 I have tested and the following code works. 我已经测试了以下代码。

I am trying to see if there is a better way of producing the same result without the extra if statement. 我试图看看是否有更好的方法来产生相同的结果,而无需额外的if语句。 I tried looking up the Arrays Class and no static method there that seems to help either. 我尝试查找Arrays类,但那里没有任何静态方法似乎对两者都有帮助。 Please advice if there is a better way of doing this method. 如果有更好的方法可以使用此方法,请提出建议。 Thanks. 谢谢。

public class ArrayTester {
    public static String[] array1 = new String[100];

    public static void main(String[] args) {
        remove(50);
        System.out.println(remove(50));
    }

    public static String remove(int name) {

        if(name == 99){
            array1[name] = null; 
            return array1[name]; 
        }

        else if (name >= 0 && name < 99){         
            for (int i=name; i < array1.length-1; i++){
                    array1[i] = array1[i+1];
            }
            return array1[name]; 
        }
        return null;  
    }
}

And with ArrayList?? 并使用ArrayList?

import java.util.ArrayList;

public class RemoveArrayListElement {

    public static void main(String[] args) {

        ArrayList<String> arlist=new ArrayList<String>();

        //<E> it is return type of ArrayList

        arlist.add("First Element"); // adding element in ArrayList
        arlist.add("Second Element");
        arlist.add("Third Element");
        arlist.add("forth Element");
        arlist.add("fifth Element");

        // remove array list element by index number
        arlist.remove(3);

        // remove ArrayList element by Object value
        arlist.remove("fifth Element");


        // get elements of ArrayList 
        for(int i=0;i<arlist.size();i++)
        {
            System.out.println("ArrayList Element "+i+" :"+arlist.get(i));
        }
    }
}

Output: 输出:

Remove ArrayList Element 0 :First Element
Remove ArrayList Element 1 :Second Element
Remove ArrayList Element 2 :Third Element 

With ArrayList is easier, isn't it? 使用ArrayList更容易,不是吗?

Looking at your code, you seem to want something like this - 查看您的代码,您似乎想要这样的东西-

if (name == 99) {
  try {
    return array1[name]; 
  } finally {
    array1[name] = null; 
  }
}
array1 = Arrays.copyOf(array1, 99);

You can simplify your code a little by excluding the if . 通过排除if可以稍微简化代码。 Unfortunately, the loop has to stay - arrays provide contiguous storage, so you need to move the data if you are to delete an item in the middle of the array. 不幸的是,循环必须保留-数组提供连续的存储,因此,如果要删除数组中间的项,则需要移动数据。

public static String remove(int index) {
    // Note the use of "index" instead of "name"
    if (index < 0 || index >= array1.length) {
        // A more common approach is to throw an exception,
        // but your code returns null for out-of-range index
        return null;
    }
    for (int i = index; i < array1.length-1 ; i++) {
        array1[i] = array1[i+1];
    }
    // Unconditionally set null in the last element of the array
    array1[array1.length-1] = null;
    return array1[index]; 
}

Sounds to me like you would be better off using an ArrayList. 在我看来,您最好使用ArrayList。 Arrays aren't really made for what you're doing. 数组并不是真正针对您正在做的事情。 But you could also just null the value at the desired location and run the java.util.Arrays.sort method on the array. 但是,您也可以在所需位置将值设置为空,然后在数组上运行java.util.Arrays.sort方法。 Something like this (I'm winging it, but this would be close): 像这样的东西(我正在给它加翅膀,但是这很接近):

public static String remove(int name) {

    String returnValue = array1[name];
    array1[name] = null;
    java.util.Arrays.sort(array1);
    return returnValue;

}

This is going to leave you with a sorted array, but you're already shifting them out of their original indices anyway so that may or may not matter to you. 这将使您拥有一个排序数组,但是无论如何您已经将它们移出了它们的原始索引,因此对您可能或不重要。

Another option would be to simply add a if (array1[index] != null) conditional to all of your code handling that array. 另一种选择是简单地向所有处理该数组的代码添加条件if (array1[index] != null) That way you wouldn't have to shift your values around in the array and your code would just skip over any null values it runs into. 这样,您就不必在数组中移动值了,您的代码只需跳过它所遇到的任何空值。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM