Find first null in an array of objects

• October 15th, 2013, 04:57 AM
iHank
Find first null in an array of objects
Hi!

I'm a java beginner and canīt figure out whatīs wrong with my code.
The question is: How do I find the first null in an array of objects, arr[10], and then add an object, obj, to that index.

I can think of something like this:

Code :

```for(int i = 0; i<10; i++) { if(arr[i] == null) { arr[i] = obj; return i; //return statement because we are inside a int-method } }```

I can also think of something like "if (arr[i] != null) then do nothing, else do arr[i] = obj", but I think thatīs an ugly solution.

Thankful for all kind of inputs

Hank
• October 15th, 2013, 05:01 AM
PhHein
Re: Find first null in an array of objects
Have you tried your solution? Does it work?
• October 15th, 2013, 05:18 AM
iHank
Re: Find first null in an array of objects
No, Iīm at work. Do you se any direct problem with my solution. The "==" for example.

My teacher wrote:

// is it a free spot at index i? if(arr[i] != null) {
arr[i] = obj;

and I don't understand it. I thought that "if(arr[i] != null)" meant that if arr[i] is not null...
• October 15th, 2013, 07:59 AM
PhHein
Re: Find first null in an array of objects
Correct! != is not equals.
• October 15th, 2013, 12:02 PM
Parranoia
Re: Find first null in an array of objects
It looks fine. Although instead of a return statement, you could use break to break out of the loop and then return.
• October 15th, 2013, 02:44 PM
iKiWiXz
Re: Find first null in an array of objects
You can try:
Code :

```for(int i = 0; i<10; i++) { try{ if(arr[i].length==0); //if null, will throw exception }catch(Exception e){ arr[i] = obj; break; } }```

It's ugly but it should work fine.
• October 15th, 2013, 03:25 PM
copeg
Re: Find first null in an array of objects
Quote:

Originally Posted by iKiWiXz
You can try:
...
It's ugly but it should work fine.

I would not recommend this approach for the following reasons a) Exceptions are meant to handle errors during runtime, not for logic b) it assumes the objects within the array have a numeric length property - if they do not then this will not compile c) other exceptions are possible within try clause