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

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

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; } } 

由于Java数组是不可resize的,因此您必须将所有内容复制到一个新的较短的数组中。

 Arrays.copyOf(original, original.length-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 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" 
 Arrays.asList(ARRAY_NAME).remove(ARRAY_NAME.length)