在数据结构类中进行的测验

时间:2011-09-17 22:36:55

标签: java

想对问题1的结果作出解释。

*** 1。以下方法的输出是什么?

public static void main(String[] args) {
    Integer i1=new Integer(1);
    Integer i2=new Integer(1);
    String s1=new String("Today");
    String s2=new String("Today");

    System.out.println(i1==i2);
    System.out.println(s1==s2);
    System.out.println(s1.equals(s2));
    System.out.println(s1!=s2);
    System.out.println( (s1!=s2) || s1.equals(s2));
    System.out.println( (s1==s2) && s1.equals(s2));
    System.out.println( ! (s1.equals(s2)));
}

答案:

false
false
true
true
true
false
false

4 个答案:

答案 0 :(得分:5)

我认为重点是==比较两个对象引用以查看它们是否引用同一个实例,而equals比较这些值。

例如,s1和s2是两个不同的字符串实例,因此==返回false,但它们都包含值"Today",因此equals返回true。

答案 1 :(得分:5)

Integer i1=new Integer(1);
Integer i2=new Integer(1);
String s1=new String("Today");
String s2=new String("Today");

// do i1 and 12 point at the same location in memory?  No - they used "new"
System.out.println(i1==i2);

// do s1 and s2 point at the same location in memory?  No - the used "new"
System.out.println(s1==s2);

// do s1 and s2 contain the same sequence of characters ("Today")?  Yes.
System.out.println(s1.equals(s2));

// do s1 and s2 point at different locations in memory?  Yes - they used "new"
System.out.println(s1!=s2);

// do s1 and s2 point to different locations in memory?  Yes - they used "new".  
// Do not check s1.equals(s2) because the first part of the || was true.
System.out.println( (s1!=s2) || s1.equals(s2));

// do s1 and s2 point at the same location in memory?  No - they used "new".  
// do not check s1.equals(s2) because the first part of the && was false.
System.out.println( (s1==s2) && s1.equals(s2));

// do s1 and s2 not contain the same sequence of characters ("Today")?  No.   
System.out.println( ! (s1.equals(s2)));

答案 2 :(得分:1)

请记住IntegerString是对象,==运算符会比较这两个指针的内存地址,而不是实际的对象本身。因此,前{2} ==将为假,因为i1i2不是同一个对象。如果初始化是:

Integer i1=new Integer(1);
Integer i2=i1;

然后第一个println()就是真的。

s1.equals(s2)是比较对象中的相等性的正确方法。 String.equals()方法将检查字符串是否相等,因此“Today”和“Today”是相等的字符串。

s1!=s2为真,因为s1和s2是不同的对象,类似于==

的i1和i2问题

其余的应该是非常简单的布尔操作。

答案 3 :(得分:0)

特别是哪些结果? this有帮助吗?