==和equals

==和equals

==:

  • 若是基本数据类型比较,则只比较两个数值是否相等
  • == 比较引用型类型 则比较的是地址
int i = 3;
int j = 3;
double d = 3.0;
char c = 3;
System.out.println(i == j); //true
System.out.println(i == d); //true
System.out.println(i == c); //true

char a = 97;
System.out.println(a == 'a'); //true

char b = 98;
System.out.println(b == 98); //error

equals

  • 若没有重写object中equals()方法,则底层是 ==
  • 若重写了equals()方法,则基本上根据按照值比。
//1. Object中equals方法
public boolean equals(Object obj) {
        return (this == obj); //底层是  ==
    }
//2 .String中equals方法  底层是比较值
public boolean equals(Object anObject) {
        if (this == anObject) {
            return true;
        }
        if (anObject instanceof String) {
            String anotherString = (String)anObject;
            int n = value.length;
            if (n == anotherString.value.length) {
                char v1[] = value;
                char v2[] = anotherString.value;
                int i = 0;
                while (n-- != 0) {
                    if (v1[i] != v2[i])
                        return false;
                    i++;
                }
                return true;
            }
        }
        return false;
    }
posted @ 2021-01-24 10:35  先生胡  阅读(46)  评论(0编辑  收藏  举报