web-dev-qa-db-fra.com

Comment supprimer le dernier élément d'un tableau?

Maintenant, je travaille avec le retour arrière récursif, ma tâche est de trouver le chemin le plus long du labyrinthe, la masse est présentée comme le champ recouvert des coordonnées et les coordonnées des murs sont douloureuses dans le fichier . I ont fait un analyseur syntaxique pour analyser le fichier d'entrée et construire les murs, mais j'ai aussi stocké ces coordonnées dans le tableau d'un type d'objet Coordinate, afin de vérifier s'il est possible de déplacer le morceau suivant du "serpent" sur le champ suivant , alors j’ai créé cette méthode, j’ai compris qu’il me faudrait une méthode pour supprimer la dernière coordonnée du tableau lorsque j’utiliserai le retour en arrière, comment puis-je le faire? L’objectif n’est pas d’utiliser des listes de tableaux ou des listes chaînées des tableaux! Je vous remercie!

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;

 }

 }

Et 

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

 }
8
Andrey Liberty

Comme les tableaux Java ne sont pas redimensionnables, vous devrez tout copier dans un nouveau tableau plus court.

Arrays.copyOf(original, original.length-1)
57
Marko Topolnik

Je sais que c'est un très vieux fil. Pourtant, la réponse approuvée elle-même ne fonctionnait pas pour moi. Et voici comment je l'ai résolu.

Créez une méthode comme celle-ci:

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()]);
}

Alors appelé comme ça:

String lines[] = {"One", "Two", "Three", "Four", "Five"};
lines = sliceArray(lines, 0, 3);

Cela se traduira par:

"One", "Two", "Three", "Four"

Maintenant, je peux couper le tableau de la manière que je veux!

lines = sliceArray(lines, 2, 3);

Cela se traduira par:

"Three", "Four"
2
    @Test
    public void removeLastElement() {

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

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

    System.out.println(Arrays.toString(removedElement));
    }
0
Mahendra Sri