1.int[] x = new int[]{3,1,2,4};
  int[] y = new int[]{3,1,2,4};
  
  ①System.out.println(x == y);                打印为false;
  ②System.out.println(x.equals(y));           打印为false;这个为什么返回的是false??
  ③System.out.println(Arrays.equals(x, y));   打印为true;  String aa = "123";
  String bb = "123";
  ④System.out.println(aa == bb);              打印为true
  ⑤System.out.println(aa.equals(bb));         打印为true  String cc= new String("123");
  String dd= new String("123");
  ⑥System.out.println(cc == dd);              打印为false
  ⑦System.out.println(cc.equals(dd));         打印就为true  疑问:
  1).②为什么打印为false?equals不是比较两个对象里面存放的内容是否想相等吗?
  2) .String aa = "123";和String aa= new String("123");的区别是什么?
      为什么④和⑥打印的结果不同?equals

解决方案 »

  1.   

    数组的比较用 Arrays.equals(a,b);
    Java字符串是不可变对象,所以所有相同的字面字符串都是同一个对象,所以④是true
    String aa= new String("123")是新建了个对象,所以⑥是false。
      

  2.   

    1、②应该是调用object类的equals方法,要想使用equals比较需要自己重写该方法2、String aa = "123";会把123放到常量池中,两个String其实指向同一个对象
    String aa= new String("123")不会,所以不要这么写!大概就这样啦吧!
      

  3.   

    1、==  比较的是 对象的内存地址,这里的x y  是分别创建了两个对象,内存地址不同所以false
    2、equals ,,你可以看看Object的equals方法,
        public boolean equals(Object obj) {
    return (this == obj);
        }
    它比较的也是内存地址,除非重写equals方法
    3、Arrays 自带的比较数组是否相等的方法,所以true4、因为没有new String()所以在缓存区里面,同样Integer i =1; 作比较也是一样的效果
    5、比较的是值,所以true6、new了一个新的String 所以这里会重新分配内存地址,地址不一样所以false
    7、比较的是值,所以true这里是String类重写了的equals方法:public boolean equals(Object anObject) {
    if (this == anObject) {
        return true;
    }
    if (anObject instanceof String) {
        String anotherString = (String)anObject;
        int n = count;
        if (n == anotherString.count) {
    char v1[] = value;
    char v2[] = anotherString.value;
    int i = offset;
    int j = anotherString.offset;
    while (n-- != 0) {
        if (v1[i++] != v2[j++])
    return false;
    }
    return true;
        }
    }
    return false;
        }
      

  4.   

    4和6不同原因是 
    String aa = "123";
    String bb = "123";
    这个时候 aa和bb是指向同一个内存地址而NewString(“123”)是创建对象 会重新分配内存地址
      

  5.   

    equals()是object的一个方法,用来比较两个对象的地址,但string和Integer重写了这个方法,所以这两个类的equals()方法是比较的两个对象的内容,至于其他的类,只要没重写equals方法的肯定还是继承的object类里的equals方法,那就是比较地址,即使对象内容一样,返回的还是false,默认的equals 是比较引用的,即比较对象的内存地址只有这样才能相等 。
      ==用于比较引用和比较基本数据类型时具有不同的功能:
      比较基本数据类型,如果两个值相同,则结果为true,而在比较引用时,如果引用指向内存中的同一对象,结果为true