包装类的比较
一、前言:
java中 ,包装类是一个对象,也是一个具体的数值。对于对象比较可以用 equals()方法,对于数值的比较可以用 == 进行比较
二,代码比较:
1.
import java.math.BigDecimal;
import java.math.BigInteger;
import java.util.*;
public class Main3 {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
Integer a = 120;
Integer b = 120;
if(a==b) {
System.out.println("饭饭最美");
}
if(a.equals(b)) {
System.out.println("洋洋最帅");
}
}
}
运行:
2.
import java.math.BigDecimal;
import java.math.BigInteger;
import java.util.*;
public class Main3 {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
Integer a = 130;
Integer b = 130;
if(a==b) {
System.out.println("饭饭最美");
}
if(a.equals(b)) {
System.out.println("洋洋最帅");
}
}
}
运行:
三、原因分析
1、通过实验代码可以看到, a2 == b2 的结果与 a1==b1 结果不一样。
2.从jdk1.5开始,Integer提供了一个内部类,IntegerCache , 数值范围在 Integer
(-128 ~ 127)之间(byte 类型的范围 ),是不会新建对象,调用的是数据缓冲池中的值。
四、最终结论
总结: 在byte类型范围内, 包装类用 == 和 equals()方法比较值是一样的,超出byte范围, == 即使数值结果一样,但是 == 返回的false,因为 Integer 底层新建了对象,不是同一个地址值。
结论: java中包装类请使用 equals()方法进行比较!
五.例题:
题目链接:https://www.dotcpp.com/oj/problem1458.html
import java.math.BigDecimal;
import java.math.BigInteger;
import java.util.*;
public class Main3 {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
while (sc.hasNext()) {
int n = sc.nextInt();
sc.nextLine();
List<Integer>lists = new ArrayList<>();
while(n-->0) {
String str = sc.nextLine();
String []strs = str.split(" +");
for (int i = 0; i < strs.length; i++) {
if(!strs[i].equals(" ")) {
lists.add(Integer.parseInt(strs[i]));
}
}
}
Object []arr = lists.toArray();
Arrays.sort(arr);
int duan = 0;
int chong = 0;
for (int i = 1; i < arr.length; i++) {
if((Integer)(arr[i])-(Integer)(arr[i-1])==2) {
duan = (Integer)arr[i]-1;
}else if((Integer)arr[i]==(Integer)arr[i-1]) {
//else if((Integer)arr[i]==(Integer)arr[i-1]);
chong = (Integer)arr[i];
}
}
System.out.println(duan+" "+chong);
}
}
}
测评结果:
错误
分析:
改正:
import java.math.BigDecimal;
import java.math.BigInteger;
import java.util.*;
public class Main3 {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
while (sc.hasNext()) {
int n = sc.nextInt();
sc.nextLine();
List<Integer>lists = new ArrayList<>();
while(n-->0) {
String str = sc.nextLine();
String []strs = str.split(" +");
for (int i = 0; i < strs.length; i++) {
if(!strs[i].equals(" ")) {
lists.add(Integer.parseInt(strs[i]));
}
}
}
Object []arr = lists.toArray();
Arrays.sort(arr);
int duan = 0;
int chong = 0;
for (int i = 1; i < arr.length; i++) {
if((Integer)(arr[i])-(Integer)(arr[i-1])==2) {
duan = (Integer)arr[i]-1;
}else if((Integer)arr[i]-(Integer)arr[i-1]==0) {
chong = (Integer)arr[i];
}
}
System.out.println(duan+" "+chong);
}
}
}
测评:
正确