0

我正在尝试以下代码:

import java.util.Stack;
public class HelloWorld{

 public static void main(String []args){
    Stack s=new Stack();
    s.push(5-4);
    s.push(9);
    s.push(51);
    if(s.get(1).equals("9"))
        System.out.println("yes its comparable");
    System.out.println(s.get(1));

 }
}

实际输出为:

9

我希望输出是:

yes its comparable
9

我无法弄清楚。我也尝试过 s.get(1)=="9" 但它也不起作用。这背后的关键可能是什么?它们都不是字符串吗?或者一个是字符串,一个是对象,但它们仍然具有可比性。有人可以启发我吗?

4

5 回答 5

7

9是一个整数。"9"是一个字符串。

s.get(1).equals("9"); // false
s.get(1).equals(9); // true
于 2013-08-16T11:49:15.953 回答
3

9是一个Integer并且"9"是一个String

因此它们不相等。

于 2013-08-16T11:49:23.103 回答
3

您正在比较 2 种不同的类型 -StringInteger. 使用引用类型Stack可以防止这种混淆

Stack<Integer> s=new Stack<Integer>();

使用原始类型

Stack s=new Stack();

导致使用对象类型,例如,当

s.push(5-4);

被调用,它被自动装箱成一个Integer类型。然后表达式

s.get(1).equals("9"))

评估false为该equals方法在进行比较之前检查类型

if (obj instanceof Integer) {
   return value == ((Integer)obj).intValue();
}
return false;
于 2013-08-16T11:50:43.547 回答
3
  if(s.get(1).equals("9"))
  System.out.println("yes its comparable");  //This prints when if condition datisfied
  System.out.println(s.get(1)); // This is run always

确保使用括号

 if(condition){
    // if satisfied condition execute this 

   }

我认为下面的代码是你所期待的

    if(s.get(1).equals(9)) // use int value not String 
        {
            System.out.println("yes its comparable");
            System.out.println(s.get(1));
        }
于 2013-08-16T11:51:15.003 回答
2

堆栈中的 9(整数)和“9”(字符串)不相等。要比较它们,请使用:

s.get(1).toString().equals("9")

或者

s.get(1).equals(Integer.parseInt("9"))
于 2013-08-16T11:59:58.883 回答