在Java中使用.equals方法的正确方法是什么? [英] What is the proper way to use a .equals method in Java?

查看:296
本文介绍了在Java中使用.equals方法的正确方法是什么?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我和我的CompSci教授谈话,他建议所有的字符串 .equals 方法写成:

I was talking with my CompSci professor and he suggested that all String .equals methods be written as:

"Hello World".equals(fooString);

而不是:

fooString.equals("Hello World");

这两行都编译,但我想知道第一种方法有什么好处?我一直做它的后一种方式。这是错误吗?

Both of these lines compile, but I was wondering what are the benefits of the first way? I've always done it the latter way. Is this wrong? What is common/conventional?

推荐答案

第一种方法可确保您不会收到 NullPointerException 您执行比较。

The first way ensures that you will not receive a NullPointerException when you perform the comparison. This Exception is thrown (occurs) when you try to invoke a method on an object that doesn't exist.

但是,作为一个注释,我非常,很少实际看到这种技术或编码风格在合法的生产环境中使用。这有两个原因。

As a note, though, I have very, very rarely actually seen this technique or coding style used in a legitimate production environment. There are two reasons for this.

首先,你编写的程序几乎总是想做一些特殊的或不同的变量包含 null <强>。这是因为它通常表示代码函数的某些其他部分的错误或需要解决的特殊情况。因此,在对象(在这种情况下,您的 String fooString )上的任何比较或方法调用之前,应始终进行空检查。

First, programs you write will almost always want to do something special or different in the case that your variable contains null. This is because it usually indicates an error in some other part of the code's function or a special case that needs to be addressed. As such, null checking should always occur before any comparisons or method calls on the object (in this case, your String fooString).

其次, fooString.equals(Hello World)只是趋向于使您的代码稍微更可读。第一种技术在代码中的逻辑意义需要几秒钟的时间才能正确处理,并且当你撇去几百或几千行代码时,很容易产生判断错误。这实际上比它听起来不那么平凡,因为在工作世界中,有很多非常古老的程序,在没有任何知道他们的人之前,他们修补了,以解决这个问题。代码可读性对于公司执行快速分类和解决长期问题的能力有巨大的贡献。

Second, fooString.equals("Hello World") just tends to make your code slightly more readable. The logical significance of the first technique in your code takes a few seconds to process correctly, and it is easy to make an error of judgment when you are skimming over hundreds or thousands of lines of code. This is actually much less trivial than it sounds, because in the working world, more often than not, there are very large and very old programs that will be patched by people who knew nothing about them before glancing at them to solve the problem. Code readability contributes in a huge way to a company's ability to perform fast triage and solve long term problems.

这篇关于在Java中使用.equals方法的正确方法是什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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