So, I saw a video of a guy who seemed to know programming pretty well and he initialized a java array with -1's instead of using null. Is there something wrong with null? He was using the -1 to know which elements weren't being used yet in a hash table. i.e. he was only storing positive numbers.
So, I'm wondering if using null for unused elements is ok?
Three answers:
2014-06-30 23:31:47 UTC
Null is fine as long as the array isn't being called on to do an action before given a value. I see where he was going with by having -1, essentially the 'false' to what would otherwise be a true. Since he would be replacing it all with positive numbers later on, it makes sense, perhaps in his mind it works easiest for him to see.
To answer your question, null values for unused elements are ok.
?
2014-06-30 23:32:35 UTC
well im kind of a rookie on java aswell but if u leave em with null and then u use the value when it compiles u might get an NullPointerException
?
2014-06-30 22:47:17 UTC
You should try and see what happens! I'm not familiar with java syntax, so no code for you from me.
ⓘ
This content was originally posted on Y! Answers, a Q&A website that shut down in 2021.
Continue reading on narkive:
Search results for 'Is using java arrays with null as empty ok?' (Questions and Answers)