【发布时间】: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