Java 在数据结构课上进行的测验

Java 在数据结构课上进行的测验,java,Java,想要解释问题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.p

想要解释问题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

我认为主要的一点是==比较两个对象引用,看它们是否引用同一个实例,而equals比较值


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

哪个结果特别重要?有帮助吗?

请记住整数和字符串是对象,==运算符比较这两个指针的内存地址,而不是实际对象本身。所以前2==将为false,因为i1与i2不是同一个对象。如果初始化是:

Integer i1=new Integer(1);
Integer i2=i1;
那么第一个println应该是真的

s1.Equals2是比较对象中相等性的正确方法。equals方法将检查字符串是否相等,因此今天和今天是相等的字符串

s1=s2是正确的,因为s1和s2是不同的对象,类似于i1和i2的问题==

剩下的应该是非常简单的布尔运算。

你认为它做什么?如果我们知道这一点,我们可以更好地帮助你。
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)));