Java If-statement - 检查字符串对变量还是变量对字符串?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/1247154/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-12 07:24:52  来源:igfitidea点击:

If-statement - Check String against variable or variable against String?

javaif-statement

提问by Tommy

Possible Duplicates:
Gracefully avoiding NullPointerException in Java
Multilingual fields in DB tables

Exact duplicate

Gracefully avoiding NullPointerException in Java

可能的重复:在数据库表
中的 Java多语言字段中优雅地避免 NullPointerException

完全重复

在 Java 中优雅地避免 NullPointerException

What do you like more? I just hate seeing the last one. It just seems backwards.

你更喜欢什么?我只是讨厌看到最后一个。它似乎只是倒退。

String randomtext = "stack overflow";

if(randomtext.equals("stack overflow"))
{
      //do something
}

or

或者

String randomtext = "stack overflow";

if("stack overflow".equals(randomtext))
{
     //do something
}

采纳答案by Mehrdad Afshari

Contrary to what some people think, these two are not functionally equivalent.The first one will throw a NullPointerExceptionif the randomtextis nullwhile the second one won't. This is why I'd choose the latter.

与某些人的想法相反,这两者在功能并不相同。NullPointerException如果randomtextnull,第一个会抛出一个,而第二个不会。这就是为什么我会选择后者。

回答by marcgg

I'd say the general opinion would go toward the first, it's more readable.

我会说一般意见会倾向于第一个,它更具可读性。

回答by Frank V

Depending on the implementation this could be personal preference.

根据实施情况,这可能是个人偏好。

Now, if there is a possibility that randomtextwill be null, I think that Merdad's post is important.

现在,如果有可能randomtext为空,我认为 Merdad 的帖子很重要。

But given your example,

但鉴于你的例子,

String randomtext = "stack overflow";

if(randomtext.equals("stack overflow"))
{
      //do something
}

it won't matter because in this case randomtextis always going to be "stack overflow".

没关系,因为在这种情况下randomtext总是“堆栈溢出”。

If you want to know which is "better", then it depends on whyit is better and that is up to you.

如果您想知道哪个“更好”,那么这取决于为什么更好,这取决于您。

回答by KM.

I prefer the first. I like to write conditions as: Test_Subject <-> Control_Value

我更喜欢第一个。我喜欢将条件写为:Test_Subject <-> Control_Value

回答by lavinio

If the string variable can be null, you always want to make the literal go first.

如果字符串变量可以是null,你总是想让文字先行。

"stack overflow".equals(randomtext)

will never cause a NullPointerException, but

永远不会导致 a NullPointerException,但是

randomtext.equals("stack overflow")

will, if randomtext == null.

会,如果randomtext == null

For that reason, although I like the variable.equals(literal), I used the former.

出于这个原因,虽然我喜欢 variable.equals(literal),但我使用了前者。

回答by Michael Behan

I'd rather

我宁愿

String randomText = "stack overflow";
String otherRandomText = "something else";

if(randomText.equals(otherRandomText))
{
   //do something
}

回答by Carl Manaster

I prefer the first as well. As Mehrdad points out, the second has a technical advantage (not throwing an exception on null), but I think it is less natural.

我也更喜欢第一个。正如 Mehrdad 指出的那样,第二个具有技术优势(不会在 null 上抛出异常),但我认为它不太自然。

I feel the same way about if (null != myVar)- it just doesn't read right, to me. Null - or the literal string - never changes, so asking if it is equal to something - although meaningful and literally correct - just seems wrongheaded.

我也有同样的感觉if (null != myVar)——对我来说,它读起来不正确。Null - 或文字字符串 - 永远不会改变,所以询问它是否等于某物 - 尽管有意义且字面上正确 - 似乎是错误的。

回答by Justin Balvanz

It depends on your purpose.

这取决于你的目的。

First of all, you shouldn't have text in your programs anyway. This is standardard practice in case you have to change that text in multiple places. So really this should be a constant or enum.

首先,无论如何,您的程序中不应包含文本。这是标准做法,以防您必须在多个位置更改该文本。所以真的这应该是一个常量或枚举。

With that in mind, you would have String randomtext = "stack overflow"; const String stackoverflow = "stack overflow";

考虑到这一点,您将拥有 String randomtext = "stack overflow"; const String stackoverflow = "堆栈溢出";

Now are you asking which looks better between randomtext.equals(stackoverflow) and stackoverflow.equals(randomtext)

现在你问哪个看起来更好 randomtext.equals(stackoverflow) 和 stackoverflow.equals(randomtext)

I don't know if it really matters. I would usually put the actual test case in the ().

我不知道这是否真的很重要。我通常会将实际的测试用例放在 () 中。

回答by Justin Balvanz

In C, or C++, the latter kind of structure might be preferred, because it's easy to confuse the following two

在 C 或 C++ 中,后一种结构可能更受欢迎,因为很容易混淆以下两种

if (randomNumber == 5) if (randomNumber = 5)

if (randomNumber == 5) if (randomNumber = 5)

The second one is syntactically valid, but is an assignment statement that always returns true, while setting randomNumber to 5. That's probably not what was intended. If you make a habit of always writing your C++ comparisons using the structure

第二个在语法上是有效的,但它是一个总是返回 true 的赋值语句,同时将 randomNumber 设置为 5。这可能不是预期的。如果您养成了始终使用结构编写 C++ 比较的习惯

if (5 == randomNumber)

if (5 == 随机数)

Then you're safer, because if you accidentally write = instead of ==, the compiler will scream at you.

那么你就更安全了,因为如果你不小心写了 = 而不是 ==,编译器会冲你尖叫。

This argument doesn't hold so much water for the original posted example, but it does explain why some programmers got into the habit of putting the constant first when doing comparisons, even though most people think the other way around seems more natural. Old habits die hard.

这个论点对于最初发布的示例并没有多大意义,但它确实解释了为什么有些程序员在进行比较时养成了将常量放在首位的习惯,尽管大多数人认为相反的方式似乎更自然。旧习难改。

回答by Chris Mazzola

I tend to check for null:

我倾向于检查空值:

if(randomtext != null && randomtext.equals("stack overflow"))
{
      //do something
}