Java静态变量导致Integer计数异常问题求助
问题分析与解决方案
嘿,这问题一看就明了啦!你碰到的核心问题是静态变量(static)的使用误区。
问题根源
你在CustomType类里把integer声明成了static:
public static int integer;
static修饰的成员变量是属于类本身的,而非类的单个实例。也就是说,所有CustomType的对象都会共享这同一个integer变量。当你循环创建3个实例时:
- 第一个实例把
integer设为0 - 第二个实例把它覆盖成1
- 第三个实例再覆盖成2
最后所有实例访问integer时,拿到的都是最后一次赋值的2,这就是Main里输出全是2的原因。
修正方案
只需要把static关键字去掉,让integer成为实例变量,这样每个CustomType对象都会拥有自己独立的integer副本:
public class CustomType { public int integer; // 移除static关键字 public CustomType(int input) { integer = input; System.out.println("CustomType: " + integer); } }
验证结果
修正后运行你的代码,输出就会和你期望的完全一致:
CustomType: 0 CustomType: 1 CustomType: 2 Main 0 Main 1 Main 2
内容的提问来源于stack exchange,提问作者Gergő Gutyina
相关产品推荐
相关产品推荐

