今天来聊聊Java中跟数值处理相关的两个类型Integer和BigDecimal。 说起这两个类型,我们肯定都不陌生,但是其中有些容易踩到的坑需要注意避让。
Integer
整型我们应该每天都会用到,但是每种语言还是有自己的特性。从敬姐刚从.NET转过来的时候踩过的一个坑说起:话说在.NET世界中,数值的基本类型和包装类型是会自动转换的,所以数值比较很自然地就会使用 a==b,但是到java这却行不通了,顿时一脸懵。
数值比较及自动装箱
- @Test
- public void Interger(){
- Integer x = 127;
- Integer y = 127;
- Integer m = 99999;
- Integer n = 99999;
- System.out.println("x == y: " + (x==y));
- System.out.println("m == n: " + (m==n));
- System.out.println("x.equals(y): " + x.equals(y));
- System.out.println("m.equals(n): " + m.equals(n));
- //执行结果
- // x == y: true
- // m == n: false
- // x.equals(y): true
- // m.equals(n): true
- }
复制代码 仔细观察可以发现,==比较,较小的两个相同的Integer返回true,较大的两个相同的Integer返回false,这是为何呢?
一起看一下Integer类的源码,发现其中的IntegerCache类。这是Java为了节省空间、提升性能采取的优化机制,常量池的大小为一个字节(-128~127)。- private static class IntegerCache {
- static final int low = -128;
- static final int high;
- static final Integer[] cache;
- static Integer[] archivedCache;
- static {
- // high value may be configured by property
- int h = 127;
- String integerCacheHighPropValue =
- VM.getSavedProperty("java.lang.Integer.IntegerCache.high");
- if (integerCacheHighPropValue != null) {
- try {
- h = Math.max(parseInt(integerCacheHighPropValue), 127);
- // Maximum array size is Integer.MAX_VALUE
- h = Math.min(h, Integer.MAX_VALUE - (-low) -1);
- } catch( NumberFormatException nfe) {
- // If the property cannot be parsed into an int, ignore it.
- }
- }
- high = h;
- // Load IntegerCache.archivedCache from archive, if possible
- CDS.initializeFromArchive(IntegerCache.class);
- int size = (high - low) + 1;
- // Use the archived cache if it exists and is large enough
- if (archivedCache == null || size > archivedCache.length) {
- Integer[] c = new Integer[size];
- int j = low;
- for(int i = 0; i < c.length; i++) {
- c[i] = new Integer(j++);
- }
- archivedCache = c;
- }
- cache = archivedCache;
- // range [-128, 127] must be interned (JLS7 5.1.7)
- assert IntegerCache.high >= 127;
- }
- private IntegerCache() {}
- }
复制代码 而对于valueOf(int i)方法,直接使用了常量池IntegerCache
[code] public static Integer valueOf(int i) { if (i >= IntegerCache.low && i |