Recently in dealing with a requirement, the requirements are described as follows: A simple process for a field of data queried in a database. Handled by: If the value of the field (the value range 0~4, possibly null) equals 0, then the default process is 1.
The test code is as follows:
1 Public classTestnull {2 3 PrivateInteger Starlevel;4 5 PublicInteger Getstarlevel () {6 returnStarlevel;7 }8 9 Public voidsetstarlevel (Integer starlevel) {Ten This. Starlevel =Starlevel; One } A - Public Static voidMain (string[] args) { -Testnull test =Newtestnull (); the -Integer Localstartlevel = -Test.getstarlevel ()! =NULL&& test.getstarlevel () = = 0? 1: Test.getstarlevel (); - + System.out.println (localstartlevel); - } + A}
Because do not want to write if-else, so the direct use of three mesh operator, the reason is certainly convenient, concise ah. Everything is done, feel yourself great!!! Then start self-test (found that the code is not a problem of children's shoes may copy the above code to execute), Error!!! Empty! Means! Needle!
To be honest, I was very confident when I was doing this code, and I've been debugging this code three times to find out why. If you have not found the reason, you can change that 1 to integer.valueof (1) or test.getstarlevel () after the semicolon
Change directly to null (which, of course, does not meet the requirements) and try again.
Problem reason: You may also find that the problem is because of the "convenient, concise" three-mesh operator expression
Analysis Reason:
1, test.getstarlevel ()! = null && test.getstarlevel () = = 0? 1: test.getstarlevel ()
Conclusion: Wrong! Because there is a branch that returns the base type number 1, and the other branch returns the immediate value of the object's invocation (the type of the value is dynamically determined at run time), the trinocular operator helps us to handle the basic type boxing operation uniformly. So null boxing is definitely a null pointer.
2,test.getstarlevel () ! = null && test.getstarlevel () = = 0? Integer.valueof (1) : test.getstarlevel ();
Conclusion: Right! Since the base type 1 has been initialized to an integer object, then this assignment expression is a direct assignment reference, so there is no problem.
3. test.getstarlevel () ! = null && test.getstarlevel () = = 0? 1: null
Conclusion: Right! The only difference between this paragraph and the first code is that Test.getstarlevel () is replaced with NULL, which eliminates the uncertainty of the runtime's ability to dynamically determine the type of return value for that branch, so it executes correctly.
The trinocular operator is easy to use, but it is necessary to pay attention to the unity of the return value type! and use and cherish!
This blog only represents a personal point of view, if there are shortcomings, please do not hesitate to advise!!!
thanks!!!
Some problems with the Java three mesh operator expression