1.比较基本类型
用== 比的是值
2.比较包装类
package com.equals;
/**
* 双等 比是否属于同一对象
* equals 比值是否相等 重写了equals方法
* @author ylq
*
*/
public class CharacterDemo {
public static void main(String[] args) {
Character c1 = new Character('s');
Character c2 = new Character('s');
System.out.println(c1==c2); //false
System.out.println(c1.equals(c2)); //true
Integer a1 = new Integer(2);
Integer a2 = new Integer(2);
System.out.println(a1==a2); //false
System.out.println(a1.equals(a2)); //true
}
}
3.比较String
public static void main(String[] args) {
String s1 = "hello";
String s2 = "hello";
System.out.println(s1==s2); //true
System.out.println(s1.contentEquals(s2));//true
String s3 = new String("hello");
String s4 = new String("hello");
System.out.println(s3==s4); //flase
System.out.println(s3.equals(s4));//true
}
- 对于静态字符串来说,如果发现字符串池中已经有了字符串,则不会创建新的字符串了
- 对于new关键字的字符串来说,==比的是是否属于同一对象,equals比的是值是否相等,重写了equals方法
4.比较对象
public static void main(String[] args) {
Person p1 = new Person("tina","女");
Person p2 = new Person("tina","女");
System.out.println(p1==p2); // false
System.out.println(p1.equals(p2)); //false
}
这里的==和equals都是比较的是否属于同一对象,因为没有重写object的equals方法
5.小结
- 基本类型用==比值
- 包装类和String类 重写了equals方法 比值
- 没有重写equals的object类 比地址是否相同