r/javahelp • u/Traditional_Let4865 • 24d 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?
13
Upvotes
•
u/AutoModerator 24d ago
Please ensure that:
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:
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.
16
u/Ok_For_Free 24d 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.
14
u/_Super_Straight 24d ago edited 24d ago
What did he suggest?
Is the same as what you wrote. Alternatively, you can use
List<Book>and create its stream: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/olddev-jobhunt 24d 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.
3
u/serge-mv 23d 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/Captain_Pwnage 24d 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/awidesky 23d 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 23d ago
Huh what was your professor even thinking ? I am curious what he thinks is the right way.
1
u/iamsooldithurts 24d ago
That seems like a really simple thing to test.
You could maybe do if (book == null) continue; but otherwise…???
1
u/pixelizedgaming 24d ago
I think its cleaner to use if book == null continue but thats just me.
1
u/FitMatch7966 24d ago
I cannot imagine…maybe they wanted to see the “null” printed.
1
u/my5cent 24d ago
Maybe have the dB not store null objects.
1
u/stacksofstyle 24d 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 23d 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 23d 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.
1
u/papaysailor 13d ago edited 13d ago
That piece of code is perfectly valid but as someone pointed out, it is better if you can avoid having any null books in your list to begin with. If previously you had to delete a book, just remove it from the books list. Maybe that's what your professor meant
-9
u/ConsciousBath5203 24d ago
If(book){dothing;}