繁体   English   中英

整数计数错误[重复]

[英]Integer counts wrong [duplicate]

这个问题已经在这里有了答案:

我正在做一个大项目,但是对于这个问题,我写了一个简单的问题示例。 我有2节课。

public class Main
{
    public static void main(String[] args)
    {
        CustomType[] customType = new CustomType[3];

        for(int i = 0; i < 3; i++)
        {
            customType[i] = new CustomType(i);
        }

        for(int i = 0; i < 3; i++)
        {
            System.out.println("Main " + customType[i].integer);
        }
    }
}

public class CustomType
{
    public static int integer;

    public CustomType(int input)
    {
        integer = input;
        System.out.println("CustomType: " + integer);
    }
}

我得到以下输出:

CustomType: 0
CustomType: 1
CustomType: 2
Main 2
Main 2
Main 2

但我想得到这个:

CustomType: 0
CustomType: 1
CustomType: 2
Main: 0
Main: 1
Main: 2

您的问题是因为您对integer使用static变量。

静态变量是对象或类(在您的情况下为CustomType类)的所有实例所共有的。 简而言之,将创建静态变量的单个副本并在类的所有实例之间共享。

因此,当在for循环的索引0处创建CustomType对象时,所有实例的静态变量值为0。 使用数组的索引位置1时,所有实例的索引位置均更改为1。 for循环在索引位置2处结束时,所有实例的static变量的值都为2。

您需要使用的是: public int integer

这将为每个CustomType对象提供其自己的单个integer变量,该变量将分配有您要查找的正确值。

如果您希望每个对象具有不同的值,则不要将变量设为静态,而是将其设置为private并使用getter方法来检索您的private var。

这个

 public static int integer;

 private int integer;

然后您的getter方法将检索数据

public int getInt()
{
    return integer;
}

static是提示。

您为什么会首先想到将static变量绑定到特定实例?

尝试使用public int integer; 而不是public static int integer; 并查看实例变量背后的魔力。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM