What are the benefits of “String”.equals(otherString)

前端 未结 7 1417
故里飘歌
故里飘歌 2021-01-19 04:57

in a tutorial (for implementing a xml parser) i saw the following code:

if( \"NODENAME\".equals(xmlreader.getNodeName()) ) {  // getNodeName() returns java.l         


        
7条回答
  •  长发绾君心
    2021-01-19 05:13

    Usually string comparison was written like that to avoid NullPointerException if xmlreader.getNodeName() is null, because then you would have

    if("NODENAME".equals(null)) {
        // ... 
    }
    

    compared to

    if(null.equals("NODENAME")) {
        // ... 
    }
    

    which would've thrown.

    This is called Yoda condition:

    enter image description here

    if you expect xmlreader.getNodeName() to be null then it's ok, otherwise I would not rely on this to avoid the exception to be thrown, you should rather deal with it earlier on in your code.

提交回复
热议问题