4 ms·
The author ( me :P ) mentions that using a.equals(b) is the correct solution right at the beginning of the post. Unfortunately this problem will continue to occ
by powatom 15y ago
The author ( me :P ) mentions that using a.equals(b) is the correct solution right at the beginning of the post. Unfortunately this problem will continue to occur as long as autoboxing exists, so I think it's a valid idea to simply enforce a rule across your team that says 'Here's how we're going to avoid autoboxing problems'. I intended this post to be more of an illustration of what autoboxing does.
With regards to your comment that the solution is not to create separate integer instances - I was attempting to show that this is a possible solution to autoboxing headaches rather than 'the correct' solution for testing integer equality, because the objects are not cached. Sometimes you want to use == for valid reasons, the problem I had was because I wasn't vigilant enough in checking my own code and used == when I shouldn't have used it in the first place.
Perhaps this post could have been written more clearly - but as it happens, you're spot on. The examples at the end of the post were intended to be potential solutions to autoboxing headaches in general, rather than a solution for my specific problem :)
- mkaufmann 15y agoOk, in that regard I think your post was very informative. Raising awareness of this language detail is very important, because it can lead to bugs which are very hard to detect. The two most valuable advices from your post is directly the first line (but I have to admit that I overread it the first time I looked at the post). And second to use some tooling like the Eclipse code checker or findbugs (which was mentioned in another comment) to make implicit conversions visible to the programmer. The only point I still disagree, though this is only a minor point, is that even with your explanation the possible solution of creating seperate instances is really no help. My point beeing that either you know that autoboxing occurs at a point and one can handle it correctly, or one doesn't know and in that case you also can't create seperate integer instances. This is from the point of view of someone who worked most of his career with Java and that line just makes my eyes bleed. But I can also understand if this looks like nitpicking to others ;)