u013337261的专栏

对于字符串变量: 1、如果使用的类重写了equals()方法,那么equals()比较的是字符串中包含的内容是否相同,否则equals()和==一样比较的是内存地址; 2、==始终比较的是两个变量的内存地址;

public class Test1 {public static void main(String[] args) {String s1,s2,s3=”abc”,s4=”abc”;s1=new String(“abc”);s2=new String(“abc”);System.out.println(s1==s2);//falseSystem.out.println(s3==s4);//trueStringBuffer buf1 = new StringBuffer(“a”);StringBuffer buf2 = new StringBuffer(“a”);System.out.println(buf1.equals(buf2));//false,//因为StringBUffer没有重写Object的equals()方法}}

对于非字符串变量: “==”和”equals”方法的作用是相同的都是用来比较其 对象在堆内存的首地址,即用来比较两个引用变量是否指向同一个对象。 另外: 1、 如果是基本类型比较,,那么只能用==来比较,不能用equals,否则编译不能通过;

public class Test2 {public static void main(String[] args) {int a = 5;int b = 4;int c = 5;System.out.println(a == b);//结果是falseSystem.out.println(a == c);//结果是trueSystem.out.println(a.equals(c));//错误,编译不能通过}}

2、 对于基本类型的包装类型,比如Boolean、Character、Byte、Shot、Integer、Long、Float、Double等的引用变量,==是比较地址的,而equals是比较内容的。

public class Test2 {public static void main(String[] args) {Integer n1 = new Integer(30);Integer n2 = new Integer(30);Integer n3 = new Integer(31);System.out.println(n1==n2);//falseSystem.out.println(n1.equals(n2));//true}}

勇气执着的背负起那厚重的行囊,奔向远方。

u013337261的专栏

相关文章:

你感兴趣的文章:

标签云: