2013-08-16 57 views
0

我想下面的代码堆栈值与字符串:在java中

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”,但它不起作用。什么可能是这背后的关键?他们都不是字符串吗?或者一个是字符串,一个是对象,但它们仍然可比。任何人都可以启发我吗?

+0

他们是可比的,但不同类型的对象(Integer和String) – greuze

回答

7

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

s.get(1).equals("9"); // false 
s.get(1).equals(9); // true 
3

9Integer"9"String

因此它们不相等。

3

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

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

使用原始类型

Stack s=new Stack(); 

原因对象被使用的类型,使得例如当调用

s.push(5-4); 

,它被自动装箱成Integer类型。然后表达

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

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

if (obj instanceof Integer) { 
    return value == ((Integer)obj).intValue(); 
} 
return false; 
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)); 
     } 
2

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

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

OR

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