“String”.equals(otherString)有什么好处? [英] What are the benefits of "String".equals(otherString)

查看:95
本文介绍了“String”.equals(otherString)有什么好处?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在教程中(用于实现xml解析器)我看到以下代码:

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

if( "NODENAME".equals(xmlreader.getNodeName()) ) {  // getNodeName() returns java.lang.String
... 
}

有没有理由写这样的字符串比较?

Is there a reason to write a string comparision like that?.

这可能是某种最佳/不良做法或代码,可能会带来一些性能上的好处。我想知道我是否应该在商业项目中使用它。

This may be some kind of best/bad practice or code like that could give some performance benefit. I would like to know if i should use this in commercial projects.

推荐答案

这样可以避免 NullPointerException。

这是尤达条件 用于解决不安全的null行为。


在编程术语中,Yoda Conditions(也称为Yoda Notation)是一种编程风格,其中两部分在条件语句中反转表达式。

In programming jargon, Yoda Conditions (also called Yoda Notation) is a programming style where the two parts of an expression are reversed in a conditional statement.

优势是


交换两个条件值不会改变程序的行为。常见的错误是意外地分配值而不是编写条件语句。

Swapping the two conditional values does not change the behavior of the program. A common mistake is to accidentally assign a value instead of writing a conditional statement.

这篇关于“String”.equals(otherString)有什么好处?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆