Funny code in src.zip

ByteBuffer.equals(Object obj)


	    byte v1 = this.get(i);
	    byte v2 = that.get(j);
	    if (v1 != v2) {
		if ((v1 != v1) && (v2 != v2))	// For float and double
		    continue;
		return false;

FloatBuffer.equals(Object obj)


	    float v1 = this.get(i);
	    float v2 = that.get(j);
	    if (v1 != v2) {
		if ((v1 != v1) && (v2 != v2))	// For float and double
		    continue;
		return false;

Can anybody explain (v1 != v1) && (v2 != v2) to me? :slight_smile:

Seems like somebody messed up with the code-generation tool.

Presumably the question you are asking is why the above code is present in ByteBuffer?
as i’m sure you’re aware for floats it’s testing for NaN values.

Looks to me like whoever wrote ByteBuffer based it upon a copy of FloatBuffer & relied a little too much on their ide’s refactoring :persecutioncomplex:

Yeah, I phrased it a bit poorly.

One would expect that this code would have been optimized to the bone (!) for all integer primitives.

I might run a benchmark to see whether it impacts performance, or that JIT is smart enough…

How’s that? NaN != NaN returns false, but any other float value returns false as well, no? It would make sense with a ==, of course.

Haha, that’s pretty good. If it was because of NaN, then of course it would make more sense to say if (v1 != NaN).

No, that check would always return false, as well.

NaN == NaN -> false

NaN != NaN -> !(NaN == NaN) -> true

oh, interesting - did not know that != is equivalent to ! ==. Thanks.

This has nothing with != vs ! == (which is logically equivalent). It’s simple as this:

NaN == NaN -> false
NaN != NaN -> true

It’s perfectly logical for NaNs, just think about it :slight_smile:

For best clarity, it’s better to use Float.isNaN method instead.

Sun’s programmers used this probably for not complicating their generator for Buffer classes. For floats/doubles it works and for integers it’s harmless.

Also I wouldn’t be worried with concrete code used in these classes, as it’s most likely replaced with optimized code by HotSpot in many places.

Noo…! You can perfectly compare floats with ==

It’s just that values that seem to be the same (by logic or by textual representation), might not be the same.

For example:
I wouldn’t be sure whether 0.50.5 == 2.00.25
yet I’m sure that 0.50.5 == 0.50.5 is true

Hehe, I can be pretty sure that 0.50.5 != 2.00.25 :wink: