Java中的==和equals
2021-03-02 01:28
标签:分配 判断 logs ase blank htm double === 作用 根据Matrix海子的博客浅谈Java中的equals和==总结 所有类直接或间接继承自Object类 Object中的equals为 可见,这时,==和equals作用相同,都是比较两个变量的地址。 Java中的==和equals 标签:分配 判断 logs ase blank htm double === 作用 原文地址:https://www.cnblogs.com/sgKurisu/p/14422276.htmlpublic boolean equals(Object obj) {
return (this == obj);
}
package com.sgkurisu.base;
public class TestEquals {
public static void main(String[] args) {
Integer a = new Integer(1);
Integer b = new Integer(1);;
System.out.println(a.equals(b));
System.out.println(a == b);
String s1 = new String("abc");
String s2 = new String("abc");
System.out.println(s1.equals(s2));
System.out.println(s1 == s2);
String s3 = "abc";
String s4 = "abc";
System.out.println(s3.equals(s4));
System.out.println(s3 == s4);
System.out.println("====================================");
//对Object中的equals方法重写
Test t1 = new Test("abc");
Test t2 = new Test("abc");
System.out.println(t1.equals(t2));
System.out.println(t1 == t2);
//未对Object中的equals方法重写
Test2 t3 = new Test2("abc");
Test2 t4 = new Test2("abc");
System.out.println(t3.equals(t4));
System.out.println(t3 == t4);
}
}
//对equals方法重写
class Test {
String s;
public Test (String s) {
this.s = s;
}
@Override
public boolean equals(Object obj) {
if (obj == this) {
return true; //判断地址
}
if (obj == null) {
return false;
}
if (obj instanceof Test) { //判断String的内容是否相等
Test t = (Test) obj;
return t.s.equals(this.s);
}
return false;
}
}
//未对equals方法重写
class Test2 {
String a;
public Test2 (String a) {
this.a = a;
}
}