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

Mis*_*ker 0 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)));
}
Run Code Online (Sandbox Code Playgroud)

回答:

false
false
true
true
true
false
false
Run Code Online (Sandbox Code Playgroud)

Mar*_*ers 5

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

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


Tof*_*eer 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)));
Run Code Online (Sandbox Code Playgroud)