1.? 先了解:string a=new string("EffieR"); 表示一定要分配內存string對象,還有相應的引? 用。string b="EffieR",此時就不再分配內存,而是建立一個新的引用b指向同一個對象"EffieR".
?
例如:
public class TestOne
?{
??? public static void main(String[] args) {
??????? String s1 = "Monday";
??????? String s2 = "Monday";
??????? if (s1 == s2)
??????????? System.out.println("s1 == s2");
??????? else
??????????? System.out.println("s1 != s2");
??? }
}
2. 如果是兩個新的對象(new),內存肯定不同,那么引用比較時也不相同。
??? 而調用equals時則是比較對象的內容,可實現我們的內容比較。
例如:
public class? Testtwo
{
?public static void main(String[] args)
?{
?? String a=new String("foo");
???????? String b=new String("foo");
??
?? System.out.println("==:"+ (a==b) );
?? System.out.println("equals: "+ a.equals(b));
??
??
?}
}
3. string.intern(); 來釋放相同值的string內存
例如:
public class TestThree
{
?/**
? * @param args
? */
?public static void main(String[] args)
?{
??// TODO Auto-generated method stub
?? String a="foo";
??
???????? String b=new String("foo").intern();
??
?? System.out.println("==:"+ (a==b) );
?? System.out.println("equals: "+ a.equals(b));
??
?}
}
4. 測試直接繼承Object的方法equals()
?例如:
class testEquals
{
?testEquals()
?{
??System.out.println("testEquals object");
?}
};
?
public class? TestFour
{
?public static void main(String[] args)
?{
??
??
???????? testEquals e1=new testEquals();
?? testEquals e2=new testEquals();
?? System.out.println(e1.equals(e2));
???
?}
}
5. 創建自己的類,覆蓋equals()
例如:
class testEquals2
{
??? private int a;
?testEquals2(int p)
?{
??
??a=p;
??
?}
?public int getMember()
?{
??return this.a;
?}
?public boolean equals(testEquals2 ob)
?{
??int a,b;
??a=this.getMember();
??b=ob.getMember();
???? return a==b;
?}
};
public class TestFive
{
?public static void main(String[] args)
?{
????? testEquals2 e3=new testEquals2(11);
?? testEquals2 e4=new testEquals2(11);
?? System.out.println(e3.equals(e4));
?}
}
6...