How to delete the last element from an array?

Andre Liberty picture Andre Liberty · Oct 14, 2014 · Viewed 73.1k times · Source

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;

 }

 }

And

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

 }

Answer

Marko Topolnik picture Marko Topolnik · Oct 14, 2014

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

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