【问题标题】:Why isn't my object being added to my array?为什么我的对象没有被添加到我的数组中?
【发布时间】:2020-03-30 19:11:38
【问题描述】:

我有一个 ManagementCompany 数据管理器类,它将有关各种属性的信息存储在名为 properties[] 的 Property(我定义的一个类)类型数组中。该类的方法之一是向该数组添加属性,称为 addProperty(Property p)。它应该采用给定的属性并将其添加到第一个可用空间中的数组中,如果有的话(如此处所示:)

Property[] properties = new Property[5];

public int addProperty(Property p) {
        if (isArrayFull())                              //Method returns true if there is no space, false otherwise                             
            return -1;
        else if (p == null)                             //Make sure p is valid          
            return -2;                                          
        for (int i = 0 ; i < properties.length; i++) {          //Loop through all elements in the array
            if (properties[i] == null) {                          //If the space is empty
                properties[i] = new Property(p);                     //Assign a new property to it
                return i;                                            //Return the index of the new property
            }
        }
        return -10;                                       //Should never happen, but need it to compile                                 
}

但是,当我创建并向数组添加属性时,只添加了第一个属性。添加第一个属性后,程序不会继续添加到第一个可用空间,而是似乎只是忽略它们。它不会替换第一个,也不会将其添加到数组中(初始化为长度为 5)。有什么建议吗?

我正在运行的测试:

ManagementCompany mgmCmp = new ManagementCompany();


Property p1 = new Property("Property 1");
mgmCmp.addProperty(p1);


Property p2 = new Property("Property 2");
mgmCmp.addProperty(p2);

System.out.println(mgmCmp.toString());

结果是: 属性1 null null null null

【问题讨论】:

  • 您需要向我们展示一个正确的minimal reproducible example - 包含我们可以测试的所有相关代码的东西。也许您的isArrayFull() 是错误的,也许您的数组没有正确初始化 - 我们无法从您向我们展示的内容中判断。
  • 请提供调用方法,似乎 addProperty 方法只被调用一次,您打印数组还是 addProperty 的每个结果?
  • 我添加了我正在使用的简单测试 - 你会看到我调用了该方法两次,每次都传递不同的对象。
  • 你能添加 show isArrayFull() 和 mgmCmp.toString()

标签: java arrays eclipse object


【解决方案1】:

只添加了第一个属性...关于原因有什么建议吗?

因为return i;。添加一个属性后退出该方法。

希望有帮助

【讨论】:

  • 这不是问题。假设您在properties[0] 处有一个非空值且properties[1] == nulltrue,循环将运行2 次并返回1
【解决方案2】:

在另一个类中发现了一个看似不相关的方法,导致对象未存储在数组中。谢谢你的建议。

【讨论】:

    猜你喜欢
    • 2014-05-14
    • 2013-11-03
    • 1970-01-01
    • 1970-01-01
    • 2013-02-19
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多