如何从数组中删除最后一个元素? [英] How to delete the last element from an array?

查看:168
本文介绍了如何从数组中删除最后一个元素?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

Now I'm working with the recursive backtracking,my assignment is to find the longest path in the maze,the mass is presented as the field covered with the coordinates,and the coordinates of the walls are sore in the file. I have made a parser to parse the input file and build the walls,but I have also stored this coordinates in the array of an object type Coordinate,to check whether it is possible to move the next piece of the "snake" on the next field,then I have created this method,now I have understood that I will need a method to remove the last coordinate from the array when I will use backtracking,how can I do it?the goal is not to use array lists or linked lists only arrays! Thank you!

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数组不可调整大小,因此您必须将所有内容复制到一个较新的较短数组中。

Since Java arrays are non-resizable, you will have to copy everything into a new, shorter array.

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

这篇关于如何从数组中删除最后一个元素?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆