equals使用总结
一、equals和==
1.equals和==的区别:前者比较内容,后者比较地址。
2.equals比较内容,但是需要覆盖这个方法,设定比较规则,JDK有一些类默认已经覆盖过了oject类的equals()方法,这些类有:java.io.file,java.util.Date,java.lang.string,包装类(Integer,Double等)
3."a"和"a "用equals比较是false,也就是说有没有空格,内容是不同的(地址也不同)。
二、常量池
Java为了提高性能,为八种基本类型和String类提供了对象池机制,当然Java的八种基本类型的包装类(Packaging Type)也有对象池机制。
public static void main(String[] args) {Integer i1 = new Integer(100);Integer i2 = new Integer(100);System.out.println(i1 == i2);System.out.println(i1.equals(i2));System.out.println("========");Integer i3 = 127;//128Integer i4 = 127;System.out.println(i3 == i4);System.out.println(i3.equals(i4));System.out.println("========");Integer i5 = 500;Integer i6 = 500;System.out.println(i5 == i6);System.out.println(i5.equals(i6));System.out.println("========");String strA1 = "test";String strB1 = "test";String strC1 = "test ";System.out.println(strA1 == strB1);System.out.println(strA1 == strC1);}falsetrue========truetrue========falsetrue========truefalse
public static void objPoolTest() {Integer i1 = 40;Integer i2 = 40;Integer i3 = 0;Integer i4 = new Integer(40);Integer i5 = new Integer(40);Integer i6 = new Integer(0);Integer i7=i5 + i6;System.out.println("i1=i2\t" + (i1 == i2));System.out.println("i1=i2+i3\t" + (i1 == i2 + i3));System.out.println("i4=i5\t" + (i4 == i5));System.out.println("i4=i5+i6\t" + (i4 == i5 + i6));System.out.println("i4=i7\t" + (i4 == i7));System.out.println();}i1=i2truei1=i2+i3truei4=i5falsei4=i5+i6truei4=i7false
public static void strPoolTest() {String str1 = "ab";String str2 = "ab";String str3 = "a";String str4 = "b";String str5 = new String("ab");String str6 = new String("ab");String str7 = new String("a");String str8 = new String("b");String str9=str7 + str8;System.out.println("str1=str2\t" + (str1 == str2));System.out.println("str1=str3+str4\t" + (str1 == str3 + str4));System.out.println("str5=str6\t" + (str5 == str6));System.out.println("str5=str7+str8\t" + (str5 == str7 + str8));System.out.println("str5=str9\t" + (str5 == str9));System.out.println();}str1=str2truestr1=str3+str4falsestr5=str6falsestr5=str7+str8falsestr5=str9false
public static void main(String[] args) {System.out.println(new StringBuffer().toString().equals(new StringBuffer("").toString()));System.out.println(new StringBuffer().equals(new StringBuffer("")));System.out.println(new StringBuffer().toString().equals(new StringBuffer("")));System.out.println(new StringBuffer().toString().contentEquals(new StringBuffer("")));}truefalsefalsetrue