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

27

现在我正在使用递归回溯法,我的任务是在迷宫中找到最长的路径,迷宫用坐标表示为覆盖区域,并且墙壁的坐标存储在文件中。我已经创建了一个解析器来解析输入文件并构建墙壁,但我还将这些坐标存储在对象类型Coordinate的数组中,以便检查是否可以在下一个方格上移动“蛇”的下一块,然后我创建了这个方法,现在我已经明白,当我使用回溯法时,我将需要一种从数组中删除最后一个坐标的方法,我该怎么做?目标不是只使用数组列表或链接列表,而是仅使用数组! 谢谢!

public class Coordinate {
int xCoord;
int yCoord;

 Coordinate(int x,int y) {
     this.xCoord=x;
     this.yCoord=y;
 }

 public int getX() {
     return this.xCoord;
 }

 public int getY() {
     return this.yCoord;
 }
 public String toString() {
     return this.xCoord + "," + this.yCoord;

 }

 }

并且

public class Row {
static final int MAX_NUMBER_OF_COORD=1000;

Coordinate[] coordArray;
int numberOfElements;


Row(){
    coordArray = new Coordinate[MAX_NUMBER_OF_COORD];
    numberOfElements=0;

   }


void add(Coordinate toAdd) {
    coordArray[numberOfElements]=toAdd;
    numberOfElements +=1;
}
boolean ifPossible(Coordinate c1){
    for(int i=0;i<numberOfElements;i++){

        if(coordArray[i].xCoord==c1.xCoord && coordArray[i].yCoord==c1.yCoord){
                return false;
            }
        }


    return true;
}

 }

2
“数组”是必须使用的吗?你可以使用对象变体,如“ArrayList”,或其他提供有用方法的方式。 - Michael Laffargue
是的,它是强制性的,我知道使用它们很愚蠢,但是它是必须的! - Andre Liberty
请使用足够长的数组,并保留一个int变量size,其中包含数组中有多少个元素是有效的。 - NomadMaker
4个回答

109

由于在Java中,数组是不可调整大小的,所以您需要将所有内容复制到一个新的较短数组中。

Arrays.copyOf(original, original.length-1)

1

我知道这是一个非常老的帖子。然而,批准的答案本身对我无效。以下是我是如何解决的。

创建一个类似于这样的方法:

String[] sliceArray(String[] arrayToSlice, int startIndex, int endIndex) throws ArrayIndexOutOfBoundsException {
    if (startIndex < 0)
        throw new ArrayIndexOutOfBoundsException("Wrong startIndex = " + startIndex);
    if (endIndex >= arrayToSlice.length)
        throw new ArrayIndexOutOfBoundsException("Wrong endIndex = " + endIndex);

    if (startIndex > endIndex) { // Then swap them!
        int x = startIndex;
        startIndex = endIndex;
        endIndex = x;
    }

    ArrayList<String> newArr = new ArrayList<>();
    Collections.addAll(newArr, arrayToSlice);
    for (int i = 0; i < arrayToSlice.length; i++) {
        if (!(i >= startIndex && i <= endIndex)) // If not with in the start & end indices, remove the index
            newArr.remove(i);
    }
    return newArr.toArray(new String[newArr.size()]);
}

然后像这样调用它:
String lines[] = {"One", "Two", "Three", "Four", "Five"};
lines = sliceArray(lines, 0, 3);

这将导致:
"One", "Two", "Three", "Four"

现在我可以以任何方式切割数组!
lines = sliceArray(lines, 2, 3);

这将导致:
"Three", "Four"

4
如果您需要指定起始和结束位置,应使用Arrays.copyOfRange - puhlen

1

我找到了一种更高效的选择:

System.arraycopy(input, 0, new_array, 0, arr.length - 1);

简而言之,这种方法会将 arr 数组的元素复制到新数组 new_array 中,但是不包括最后一个元素。然而,这种方法需要您创建和使用另一个数组,而不是原始数组。

-1
    @Test
    public void removeLastElement() {

    String[] lastElementRemoved = { "one", "two", "three" };

    String[] removedElement = Arrays.copyOf(lastElementRemoved, 2);

    System.out.println(Arrays.toString(removedElement));
    }

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接