Java 在对象数组中找到第一个空槽
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/23232020/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Find first empty slot in an array of objects
提问by Jordan.McBride
This is for a school project where we have to create an object, and then create an array of 20 objects. The object contains 1 string, and 4 doubles. I understand how to use a constructer to initialize the objects vairables. However, the part I am stumped on is how to determine the first empty space in the array. I'm assuming that each object in the array is nulluntil it is assigned variables via the constructer. How would I go about finding the first empty spot in the array?
这是一个学校项目,我们必须创建一个对象,然后创建一个包含 20 个对象的数组。该对象包含 1 个字符串和 4 个双打。我了解如何使用构造函数来初始化对象变量。然而,我难倒的部分是如何确定数组中的第一个空白空间。我假设数组中的每个对象都是空的,直到通过构造函数为其分配变量。我将如何找到数组中的第一个空位?
Forgive me if its a duplicate, but the ones I looked at either didn't have thorough questions or they were not what I think I'm looking for
如果它重复,请原谅我,但我看过的那些要么没有彻底的问题,要么不是我想我要找的
I tried to do this:
我试图这样做:
int openArray;
for(int i = 0; i<markbook.length; i++) {
if(markbook[i] = null)
{
openArray = 1;
}
}
But it didn't seem to do anything, or work.
但它似乎没有做任何事情,或工作。
-Jordan
-约旦
采纳答案by Marcinek
You are doing just fine. Your only fault is that you are using the assigne operator =
(single equals) in your if-condition.
你做得很好。您唯一的错误是您=
在 if 条件中使用了赋值运算符(单等号)。
Where you should use the comperator: ==
(double equals)
你应该在哪里使用比较器:(==
双等号)
int openArray = 0;
for(int i = 0; i<markbook.length; i++) {
if(markbook[i] == null)
{
openArray = i;
break;
}
}
And you should save i
instead of 1
. See my code example.
你应该保存i
而不是1
. 请参阅我的代码示例。