我不明白以下代码有什么问题

时间:2013-05-23 16:59:07

标签: java android if-statement

    savedInstanceState = getIntent().getExtras();
    String type = savedInstanceState.getString(TYPE);
    if(type == "tree")
    {
        setContentView(R.layout.activity_sound_tree);
    }
    else
    {
        TextView tv = (TextView) findViewById(R.id.heading_sound);
        tv.setText("'"+type+"'");
    }

我在第二个活动中使用了这段代码。我肯定知道type == tree。所以我不明白为什么第一个“if”块失败了。它总是进入“else”块,即使我100%确定类型==“树”。有人能指出我正确的方向吗?

3 个答案:

答案 0 :(得分:3)

永远不要将字符串值与==运算符进行比较。请改用equals方法。

==运算符按引用比较对象,而不是按值。

Javadoc:http://docs.oracle.com/javase/7/docs/api/java/lang/Object.html#equals(java.lang.Object)

固定代码:

savedInstanceState = getIntent().getExtras();
String type = savedInstanceState.getString(TYPE);
if(type.equals("tree"))
{
    setContentView(R.layout.activity_sound_tree);
}
else
{
    TextView tv = (TextView) findViewById(R.id.heading_sound);
    tv.setText("'"+type+"'");
}

答案 1 :(得分:0)

这看起来像classic String comparison question,请尝试

"tree".equals(type); // This is also safe from NullPointerException since you are comparing type with a constant 'tree', which is not null

为何等于?

有关使用==equals()的详细说明,请here

答案 2 :(得分:0)

使用

type.equals("tree")

而不是

type == "tree"

<强>原因

equls方法检查对象的值,其中==运算符检查它们是否是同一个对象实例。

相关问题