java 在 if 语句中使用对象...(Android)
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/2709161/
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
Using an object in an if statement... (Android)
提问by James Rattray
I have an object variable Object test = Spinner.getSelectedItem();-It gets the selected item from the Spinner (called spinner) and names the item 'test'
我有一个对象变量Object test = Spinner.getSelectedItem();- 它从微调器(称为微调器)中获取所选项目并将项目命名为“测试”
I want to do an if statement related to that object e.g:
我想做一个与该对象相关的 if 语句,例如:
'if (test = "hello") {
//do something
}'
But it appears not to work. Do I have to use a different if? or convert the object to string etc.?
但它似乎不起作用。我必须使用不同的 if 吗?或将对象转换为字符串等?
回答by staticman
The statement:
该声明:
test = "hello"
is an assignment of the string "hello" to the variable test - it doesn't do a comparison.
是将字符串“hello”分配给变量 test - 它不进行比较。
test == "hello"
is a comparison but still might not work because it compares references. Two different string instances that happen to be both "hello" may not be the same references and therefore the statement may be false.
是一个比较,但仍然可能不起作用,因为它比较了引用。碰巧都是“hello”的两个不同的字符串实例可能不是相同的引用,因此该语句可能为假。
Try:
尝试:
"hello".equals( test )
回答by Eyal Schneider
If you want to compare strings, use equals():
如果要比较字符串,请使用equals():
if ("hello".equals(test))...
回答by used2could
Make test a string and cast the results of getSelectedItem() to a string
测试一个字符串并将 getSelectedItem() 的结果转换为一个字符串
string test = (string)Spinner.getSelectedItem();
if (test == "hello")
{
//Do something
}
回答by Dean
It is also valid in saying test.equals("hello") i don't like the other way it doesn't look right in my coding style.
说 test.equals("hello") 我不喜欢它在我的编码风格中看起来不正确的另一种方式也是有效的。

