How to delete the last element from an array?

前端 未结 3 1623
情书的邮戳
情书的邮戳 2021-01-04 04:15

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 th

相关标签:
3条回答
  • 2021-01-04 05:00

    I know its a very old thread. Still the approved answer itself didn't work for me. And this is how I resolved it.

    Create a method like this:

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

    Then called it like this:

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

    This will result in:

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

    Now I can slice the array in whichever way I want!

    lines = sliceArray(lines, 2, 3);
    

    This will result in:

    "Three", "Four"
    
    0 讨论(0)
  • 2021-01-04 05:05
        @Test
        public void removeLastElement() {
    
        String[] lastElementRemoved = { "one", "two", "three" };
    
        String[] removedElement = Arrays.copyOf(lastElementRemoved, 2);
    
        System.out.println(Arrays.toString(removedElement));
        }
    
    0 讨论(0)
  • 2021-01-04 05:06

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

    Arrays.copyOf(original, original.length-1)
    
    0 讨论(0)
提交回复
热议问题