Is condition str2==null always true?

1. private boolean isSameString(String str1, String str2) 2. {
3. if(str1==null && str2!=null) return false;
4. if(str2==null && str1!=null) return false;

5. if(str1==null && str2==null) return true;

6. return (str1.equals(str2));
7. }

IDE suggests that str2==null in line 5 is redundant and is always true.

0
Avatar
Permanently deleted user


Very clever of it, and absolutely the case. Nice work on someone's part.

0
Avatar
Permanently deleted user

do you think this is a little easier to read?

private static boolean areSame(Object one, Object two){
if(one == null ^ two == null)
return false;

if(one == null && two == null)
return true;

return one.equals(two);
}

0
Avatar
Permanently deleted user

Another suggestion:


And my preferred:


0
Avatar
Permanently deleted user

And my preferred:

 private static boolean areSame3(Object one, Object two) {
> 	if (one == null || two == null)
> 		return one == two;
> 
> 	return one.equals(two);
> }
> ]]>


Hey, that's really cool; I never thought of that. With that idea, the thing can be turned into a one-liner:



Regards,
Jens

0
Avatar
Permanently deleted user

With that idea, the thing can be turned into a
one-liner:

 return one == null ? one == two : one.equals(two);
> ]]>


Which, as I just realized, should definitely be turned into an intention in the ipp.
(Dave, are you reading this?)

0
Avatar
Permanently deleted user

>

private static boolean areSame3(Object one, Object two) {
>	if (one == null || two == null)
>		return one == two;
>
>	return one.equals(two);
>}
>]]>


+1 much better understandable than the original one

0
Avatar
Permanently deleted user

Technically:

So unless you actually want the behaviour of regarding two

strings as the same string you should return false when str1 and str2 are

.

0
Avatar
Permanently deleted user

I want the method to return true when both are null.
passing noth arguments as null, it will certainly hit line 5 and will return correct value.

but as the original question was-Is it redundant...?

0
Avatar
Permanently deleted user

Yes. After line 3, if you know that str1 is null, then str2 must be null (otherwise line 3 would have returned). The analysis to figure this out looks to be pretty darn clever.

--Dave

0
Avatar
Permanently deleted user

Technically:
null != null


I've only seen this in SQL. Are there any other languages handling null like
SQL does?

IMO, someone must have been smoking something when the behaviour of
null was put into sql.

Whoever creates a logic system where (a = b or a != b) can be a false
statement may have a great head, but it's floating a little to high above
the clouds.

It may be preety for mathematic/logic investigation, but it's a fountain of
unnecessary bugs in daily use.


0

请先登录再写评论。