Java--获取数组中的最后一个元素以及除了最后一个元素剩余的其他元素

时间:2025-03-18 15:12:32

获取数组中的最后一个元素以及除了最后一个元素剩余的其他元素

废话不多说,直接上代码:

public class TestArray {

    static boolean empty(int a[]) {
        return (a.length == 0);
    }

    static int getFirst(int a[]) {
        return a[0];
    }

    static int getLast(int a[]) {
        return a[a.length - 1];
    }

    static int[] getRest(int a[]) {
        int b[] = new int[a.length - 1];
        for (int i = 0; i < b.length; i++) {
            b[i] = a[i];
        }
        return b;
    }

    public static void main(String... args) {
        int a[] = new int[24];

        for (int i = 0; i < a.length; i++) {
            a[i] = i;
        }
        System.out.println("原始数组中的所有元素:" + Arrays.toString(a));
        int last = getLast(a);
        System.out.println("数组中的最后一个元素是:" + last);
        int[] rest = getRest(a);
        System.out.println("除了最后一个元素剩余的其他元素是:" + Arrays.toString(rest));


    }

控制台输出结果:

原始数组中的所有元素:[0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23]
数组中的最后一个元素是:23
除了最后一个元素剩余的其他元素是:[0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22]

相关文章