在JDK 1.6中,String equals操作可以替换为==吗? [英] In JDK 1.6, can String equals operation can be replaced with ==?

查看:409
本文介绍了在JDK 1.6中,String equals操作可以替换为==吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

当我研究一些开源产品的源代码时,我发现代码如下:

As I study the source code of some open source products, I find code like:

if (a=="cluser")

a 是一个String变量。可以用 == 替换字符串等于操作吗?

a is a String variable. Can a String equals operation be replaced with ==?

推荐答案

您应该从不使用 == 并且几乎始终使用 equals()方法。如果两个字符串都引用同一个对象,它只能与 == 一起使用。在 String 上有 intern()方法,以返回给定字符串值的相同引用。字符串文字是隐式实现的。只有你有充分的理由,你才能使用 == 进行字符串比较,即使这样你也需要非常小心。

You should almost never use == and almost always use equals(). It will only work with == if both strings reference the same object. There's an intern() method on String to return the same reference for a given string value. String literals are implicitly interned. Only if you have a very good reason should you use == for string comparison, and even then you need to be very careful.

唯一的好理由是表现,而且非常罕见。只需优化一次您肯定知道您需要这样做。否则通常不值得麻烦。如果您正在查看一些开源代码,他们可能会遇到一种情况,即比较是在一个非常紧凑的循环中或非常频繁地调用,优化可以提供帮助。或者它只是过早优化,似乎是安全的。

The only good reason is performance, and very rarely will it matter. Only optimize once you know for sure that you need to do so. It's otherwise normally not worth the hassle. If you're looking at some open source code, they might have a case whereby the comparison is in a very tight loop or called very frequently and the optimization can help. Or it was just prematurely optimized and maybe seemed safe.

这篇关于在JDK 1.6中,String equals操作可以替换为==吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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