You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在Java数组实现的Stack中防止index被非法修改?

问题原因

你遇到的问题核心在于静态内部类的private静态成员,在外部类的main方法中是可访问的——Java中,同一个类(这里是Stack_04)内部的代码,不管是外部类方法还是静态内部类的成员,都能访问彼此的private修饰元素,哪怕是静态成员。另外,static成员属于类本身而非实例,你通过st.index访问本质上是借实例引用了类的静态成员,等价于StackArray.index。

解决方案

要避免index被任意修改,可从以下方向处理:

1. 将静态内部类改为非静态内部类(适合每个实例独立维护index的场景)

去掉index的static修饰符,同时保持private,这样外部类的main方法就无法直接访问该成员:

public class Stack_04 {

    public class StackArray {
        private int[] arr = new int[5];
        private int index = 0;
    }
    public static void main(String[] args) {
        Stack_04 outer = new Stack_04();
        StackArray st = outer.new StackArray();
        // st.index = 8; 此处编译报错,无法访问private成员
    }
}

2. 保留静态成员,通过封装限制修改(适合index为类级共享的场景)

将index设为private static,仅提供必要的公共方法来操作它,不暴露直接修改的入口:

public class Stack_04 {

    public static class StackArray {
        private static int[] arr = new int[5];
        private static int index = 0;

        // 仅提供入栈等必要操作方法,内部维护index的变更
        public static void push(int value) {
            if (index < arr.length) {
                arr[index++] = value;
            }
        }

        // 提供获取方法,不提供修改方法
        public static int getIndex() {
            return index;
        }
    }
    public static void main(String[] args) {
        // StackArray.index = 8; 编译报错
        StackArray.push(10);
        System.out.println(StackArray.getIndex()); // 仅能通过方法获取值
    }
}

注:如果需要每个实例独立维护栈,需把arr和index都改为非静态成员,同时调整方法为非静态。

3. 将静态内部类改为独立顶层类

把StackArray移到Stack_04外部作为独立类,这样外部类的main方法就无法访问它的private成员:

// 独立顶层类
public class StackArray {
    private int[] arr = new int[5];
    private static int index = 0;
}

public class Stack_04 {
    public static void main(String[] args) {
        StackArray st = new StackArray();
        // st.index = 8; 编译报错,无法访问其他类的private成员
    }
}

内容的提问来源于stack exchange,提问作者Rakesh036

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.16 19:42:47