两个interger对象之间的对比和取值范围有关,interger的取值范围在(-128~127),超出interger范围会重新创建一个interger类,会导致地址值不同,使用“==”进行对比为false;使用equals进行对比为true。
==============================
取值超出范围时的“==”比较:
public class
Main
{
public static
void
main
(
String
[]
args
) {
Integer
i1
=
100
;
Integer
i2
=
100
;
Integer
i3
=
128
;
Integer
i4
=
128
;
System
.
out
.
println
(
i1
==
i2
);//true
System
.
out
.
println
(
i3
==
i4
);//false
}
}
==============================
取值处于范围时的“==”比较:
public class
Main
{
public static
void
main
(
String
[]
args
) {
Integer
i1
=
100
;
Integer
i2
=
100
;
Integer
i3
=
127
;
Integer
i4
=
127
;
System
.
out
.
println
(
i1
==
i2
);//true
System
.
out
.
println
(
i3
==
i4
);//true
}
}
==============================
取值处于范围时的“equals”比较:
public class
Main
{
public static
void
main
(
String
[]
args
) {
Integer
i1
=
100
;
Integer
i2
=
100
;
Integer
i3
= -
129
;
Integer
i4
= -
129
;
System
.
out
.
println
(
i1
.equals(
i2)
);//true
System
.
out
.
println
(
i3
.equals(
i4)
);//true
}
}