String str = "hello";
char ch[] = {'h','e','l','l','o'};char ch1[] = str.toCharArray();   //string转换成charif(ch1 == ch)
  System.out.println("ch == c:true");
else 
  System.out.println("ch == c:false");--上述打印结果为falseif(ch1.equals(ch))
   System.out.println("true");
else                                       //结果为false
   System.out.println("false");2:
   char c[] = {'H','e','l','l','o'};
   String s = "hello";   String s2 = new String(c);     //char转换成string
   
    if(s2==s)
               System.out.println("true");
            else
               System.out.println("false");   //打印            if(s2.equals(s))
                System.out.println("true");   //打印
            else
                System.out.println("false");
   
上面为什么把string转变成char类型时,为什么用==  和 equals时打印结果均为false
而char转变为string时用== 打印也为false,而用equals时也就是比较内容时却为 true,那么为什么string转为char时比较内容还是为false,我想即使把string转变为char,或者是把char转变为string,但是给他们分配的内存地址并没有改变,只是大小改变了,所有不管是string转变为char,或者是把char转变为string,用==比较始终都为false,可是就是不明白用equals时两者得出的结论却不同

解决方案 »

  1.   

    1 char[] 比较有标准吗? 呵呵!因为没有,所以等于false啦!因为默认的equals就是==
    2 String 也是这个道理,因为String 是不可变的,所以从String->char->String 就生成了新的String 当然==是false
      

  2.   

    首先==符号和Object的equals方法是同样的效果~!因为数组是个object !所以falseString是不可变的,当你改变它的时候总能生成新的!
      

  3.   


    lz:
    if(ch1 == ch) 
      System.out.println("ch == c:true"); 
    else  
      System.out.println("ch == c:false");
    比较的是引用,引用指的是不同的对象,返回false.
    在Object中 提供的缺省实施简单引用下面等式:  
    public boolean equals(Object obj) { return (this == obj); } 
    在这种缺省实施情况下,只有它们引用真正同一个对象时这两个引用才是相等的。 
    if(ch1.equals(ch)) 
       System.out.println("true"); 
    else                                      
       System.out.println("false"); 
    数组是一个隐含的类,是object的子类,继承object的成员.所以我认为它也没有重写object的equals()方法
    所以比较的也是引用,结果也是false.String中有重写equals()方法
    public boolean equals(Object anObject)比较此字符串与指定的对象。当且仅当该参数不为 null,并且
    是表示与此对象相同的字符序列的 String 对象时,结果才为 true。 覆盖:类 Object 中的 equals
    也就是说
    String中有重写equals()方法比较的是对象,而不是引用if(s2.equals(s)) 
                    System.out.println("true");  
                else 
                    System.out.println("false"); 
    重写equals()方法,比较的是对象 ,打印true;我是java超级大菜鸟,有什么不对的,请大家指正.
      

  4.   

    支持竹子
    在你没有重写equals的情况下== 和equals的效果是一样的 
     String类重写了 equals所以String 的equals和==是不同的。