问题描述:
在刷剑指offer的时候遇到一个问题,前几个样例都过了,这个出了问题,比较两个栈顶是否相等,用的是“==”进行判断,数据量不大的时候是没有问题的,随着数据量的增加,栈顶值超过127问题就来了,两个相同的超过127的值比较返回false。
原题:
import java.util.Stack;
public class Solution {
Stack<Integer> stack1 = new Stack<>();
Stack<Integer> stack2 = new Stack<>();
public void push(int node) {
stack1.push(node);
if (stack2.isEmpty() || node <= stack2.peek()) {
stack2.push(node);
}
}
public void pop() {
//if(stack1.peek().intValue() == stack2.peek().intValue()){
//if(stack1.peek() == stack2.peek()){
if (stack1.peek().equals(stack2.peek())) {
stack2.pop();
}
stack1.pop();
}
public int top() {
return stack1.peek();
}
public int min() {
return stack2.peek();
}
}
1、先来看==和equals的区别:
==对于基本数据类型比较的是值,而对于引用类型比较的就是引用的地址,即两个引用是否指向同一个对象实例
int a = 128;
int b = 128;
System.out.println(a==b);
Integer c = 127;
Integer d = 127;
System.out.println(c==d);
Integer e = 128;
Integer f = 128;
System.out.println(e==f);
true
true
false
equals 对于没有重写equals方法的引用类型的比较和==是一样的,只是String,包装类等重写了equals方法,所以按重写后的规则进行比较,比较的是对象指向的内容是否相等;对于基本数据类型则没有equals方法
stack1.peek() == stack2.peek(),如果数值在-128–127之间。比较的是数值
原因:
查看Integer源码发现,Integer内部有一个静态变量缓存池IntegerCache,里面声明了一个Integer[]数组,范围-128——127,Jvm在运行时创建了一 个缓存区域并创建了一个integer的数组。 这个数组存储了-128至127的值。因此如果integer的值在- 128至127之
间,则是去缓存里面获取。
private static class IntegerCache {
static final int low = -128;
static final int high;
static final Integer cache[];
static {
// high value may be configured by property
int h = 127;
String integerCacheHighPropValue =
sun.misc.VM.getSavedProperty("java.lang.Integer.IntegerCache.high");
if (integerCacheHighPropValue != null) {
try {
int i = parseInt(integerCacheHighPropValue);
i = Math.max(i, 127);
// Maximum array size is Integer.MAX_VALUE
h = Math.min(i, Integer.MAX_VALUE - (-low) -1);
} catch( NumberFormatException nfe) {
// If the property cannot be parsed into an int, ignore it.
}
}
high = h;
cache = new Integer[(high - low) + 1];
int j = low;
for(int k = 0; k < cache.length; k++)
cache[k] = new Integer(j++);
// range [-128, 127] must be interned (JLS7 5.1.7)
assert IntegerCache.high >= 127;
}
private IntegerCache() {}
}
stack1.peek().intValue() == stack2.peek().intValue(),intValue()方法,可以拆箱,把包装类型转换成基本数据类型,这个时候比较的就是数值,