Sorry, your browser cannot access this site
This page requires browser support (enable) JavaScript
Learn more >

==:

  1. == 比较的是两个操作数时候是同一个对象,比较引用
  2. 两边操作数必须是同一类型才能编译通过
  3. 比较的是地址,如果是具体的数字比较,值相等则为true。
1
2
3
4
5
6
7
8
9
10
11
12
13
public class JavaEqual {
public static void main(String[] args) {
int a = 10;
double b = 10;
if(a==b){
System.out.println("==");
}
else{
System.out.println("!=");
}
}
}
// 输出: ==

equal:

  1. equals比较两个对象的内容,如果没有进行重载,测试出的就是Object的equal方法,返回的就是==的判断。
  2. String str = “hello”; 先在内存中找是不是有”hello”这个对象,如果有,就让str指向那个”hello”.如果内存里没有”hello”,就创建一个新的对象保存”hello”. String str=new String (“hello”) 就是不管内存里是不是已经有”hello”这个对象,都新建一个对象保存”hello”。
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
/**
String 类对equals的重写
*/
public boolean equals(Object anObject) {
if (this == anObject) {
return true;
}
if (anObject instanceof String) {
String anotherString = (String)anObject;
int n = count;
if (n == anotherString.count) {
char v1[] = value;
char v2[] = anotherString.value;
int i = offset;
int j = anotherString.offset;
while (n-- != 0) {
if (v1[i++] != v2[j++])
return false;
}
return true;
}
}
return false;
}

评论