首页 诗词 字典 板报 句子 名言 友答 励志 学校 网站地图
当前位置: 首页 > 教程频道 > 开发语言 > 编程 >

equals跟==

2012-10-08 
equals和public static void main(String[] args) {String s1 new String(a)String s2 new Strin

equals和==

public static void main(String[] args) {String s1 = new String("a");String s2 = new String("a");System.out.println(s1==s2);System.out.println(s1.equals(s2));s1=s2;System.out.println(s1==s2);System.out.println(s1.equals(s2));}

----------------------------------------

结果
false
true
true
true
----------------------------------------
说明: ==比较是两个对象的引用,equals是比较对象的内容。
Object中equals 源码
 public boolean equals(Object obj) {return (this == obj);    }


如果对象没有重写equals方法,则==和equals是相同的。

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;    }

热点排行