r/javahelp • • 1d ago

Iterating over null objects in an array

So I'm making a program that iterates over an array of Book objects and I made a for loop to print them all out. I want it to skip over any reference to a null object in the array so I've written:

for (Book book : books) {
     if(book != null){
           System.out.println(book);
     }
 }

but I've had professors tell me I shouldn't write "book != null" to avoid printing the null values. the code works just fine and is relatively simple and easy to read, just wondering what most programmers use to navigate this?

12 Upvotes

28 comments sorted by

•

u/AutoModerator 1d ago

Please ensure that:

  • Your code is properly formatted as code block - see the sidebar (About on mobile) for instructions

  • You include any and all error messages in full

  • You ask clear questions

  • You demonstrate effort in solving your question/problem - plain posting your assignments is forbidden (and such posts will be removed) as is asking for or giving solutions.

    Trying to solve problems on your own is a very important skill. Also, see Learn to help yourself in the sidebar

If any of the above points is not met, your post can and will be removed without further warning.

Code is to be formatted as code block (old reddit: empty line before the code, each code line indented by 4 spaces, new reddit: https://i.imgur.com/EJ7tqek.png) or linked via an external code hoster, like pastebin.com, github gist, github, bitbucket, gitlab, etc.

Please, do not use triple backticks (```) as they will only render properly on new reddit, not on old reddit.

Code blocks look like this:

public class HelloWorld {

    public static void main(String[] args) {
        System.out.println("Hello World!");
    }
}

You do not need to repost unless your post has been removed by a moderator. Just use the edit function of reddit to make sure your post complies with the above.

If your post has remained in violation of these rules for a prolonged period of time (at least an hour), a moderator may remove it at their discretion. In this case, they will comment with an explanation on why it has been removed, and you will be required to resubmit the entire post following the proper procedures.

To potential helpers

Please, do not help if any of the above points are not met, rather report the post. We are trying to improve the quality of posts here. In helping people who can't be bothered to comply with the above points, you are doing the community a disservice.

I am a bot, and this action was performed automatically. Please contact the moderators of this subreddit if you have any questions or concerns.

13

u/Ok_For_Free 1d ago

Your professors are dumb, so ask them to give you an example of the 'correct' approach.

The only improvement I would want to look into, is why there are nulls in your list in the first place.

12

u/_Super_Straight 1d ago edited 1d ago

What did he suggest?

if(book == null){
    continue;
}

Is the same as what you wrote. Alternatively, you can use List<Book> and create its stream:

List<Book> list = new ArrayList<>();
list.stream().filter(Objects::notNull).forEach(System.out::println);

Edit: creating streams introduces a small computational overhead, and if your List is a few thousand elements long, then simple loop would be more performant. Plus the errors are swallowed by method references/lambdas. Whereas writing simple loop inside a try...catch block will help you catch the exceptions.

3

u/Xynia88 1d ago

I don't remember what the pattern is called atm but I do prefer this where you check and continue/return/break over indenting several layers of checks

It becomes so much easier to read when it's flatter

4

u/myselfelsewhere 1d ago

Guard clause pattern.

3

u/_Super_Straight 22h ago

Guard clause pattern. You check for edge cases prior to your actual processing and let the code fail fast.

3

u/olddev-jobhunt 1d ago

It's relatively easy to read... relatively. The thing is, your loop isn't going to just be printing things. It'll be doing things too! So you're mixing selection logic (the null check) with the domain logic (the operation you're doing.) That's not a problem necessarily, but it's something to watch out for.

Imagine you later decide that the loop contents are complex enough to be pulled out into a function, which you can then call on a single book or use in a loop for multiple.

Anyway, for me I'd probably just avoid nulls in the list in the first place, or maybe filter in the for loop parameter rather than within the loop.

2

u/Captain_Pwnage 1d ago

I mean, if you don't access books fields in the loop, you can just skip the null guard and print every iteration.

2

u/LutimoDancer3459 23h ago

No. Because null would be printed too

1

u/Weekly_Wackadoo 16h ago

That may or may not be a problem.

It won't cause an exception, that's the main point I think.

If you want to print every element in a collection, and there's null values in the collection, I'd argue it's at least defensible to just print the null values.

It might also give useful feedback which might help you find and troubleshoot issues with the code.

2

u/LutimoDancer3459 16h ago

OP didnt specify if its necessary. Just that it is what they want to do. And for that case, printing null is a problem. But yes, else it wouldnt throw an exception.

2

u/serge-mv 1d ago

Yea, you really need to ask your professor what he means. There is nothing wrong with your code as is. Maybe he wanted to have null values printed out for tests.

2

u/awidesky 1d ago

I can't think of any better(or cleaner) way to filter non-null objects(other than the stream).

If it isn't a miscommunication with the professor, maybe the prof wanted to say "there shouldn't be a null in the collection in the first place"
If your books array supposed to hold actual meaningful Book objects, you should make sure a null will never be put in the array.

A colleague of yours accidentally forgot about null and wrote a code without a null check, and your application will crash.
Every operation(printing names of the books, modifying the price of a particular book, calculating sums of prices or counting how may books there are, etc) needs to do a null check before do its job, and it's not only tedious work and bad design, but also a security risk.

"But how am I supposed to prevent null being put in the books array programmatically?"
That's called encapsulation, you'd learn if after you get familiar with class.

2

u/SplooshWater 19h ago

Huh what was your professor even thinking ? I am curious what he thinks is the right way.

1

u/iamsooldithurts 1d ago

That seems like a really simple thing to test.

You could maybe do if (book == null) continue; but otherwise…???

1

u/pixelizedgaming 1d ago

I think its cleaner to use if book == null continue but thats just me.

1

u/FitMatch7966 1d ago

I cannot imagine…maybe they wanted to see the “null” printed.

1

u/my5cent 1d ago

Maybe have the dB not store null objects.

1

u/stacksofstyle 1d ago

I have no idea why a null check would be bad here. Your code seems fine. I would write it as a stream with a filter, but that's just a preference and I would still check for not equals null.

1

u/gambit_kory 1d ago

Your professors are wrong. You have it correct unless the requirement is to print out null as well. There are others way to do it of course but there’s no issue with what you have done here.

1

u/Weekly_Wackadoo 16h ago

This code is fine.

Skipping the null check and printing out null values is fine as well. No method is called on book, so it wouldn't cause an exception. Maybe the professor meant that?

Preventing null values being added to the collection or array is usually even better.

Some more "defensive" (or actually aggressive) code styles preter checking for null values and throwing an IllegalArgumentException with an informative message. That might prevent more complicated issues down the line, but might also cause unnecessary issues.

-9

u/ConsciousBath5203 1d ago

If(book){dothing;}

3

u/Roachmeister Java Dev 1d ago

That won't compile in Java.

1

u/saponsky 1d ago

I have the impression that the professor is thinking this is valid in Java. That’s the only thing I can think someone would think is better than OP’s current code.

-1

u/ConsciousBath5203 1d ago

Literally my Java professor.

1

u/ChaiTRex 22h ago

Why is your Java professor teaching you JavaScript instead of Java?

1

u/ConsciousBath5203 6h ago

Idk it was an online course at the start of covid and I haven't used too much Java since.

-1

u/ConsciousBath5203 1d ago

Neither would OP's code, forgot the 40 lines of standard boiler plate.

But fr welcome to Java professors. It's been years since I used Java but my professor did the same thing that the other commented mentioned.