Integer源码阅读
Integer源码分析
一道面试题
/** * @author xuelongjiang */
public class Test6 {
public static void main(String[] args) {
Integer var0 = 100;
Integer var1 = 100;
Integer var2 = 130;
Integer var3 = 130;
System.out.println(var0 == var1);
System.out.println(var2 == var3);
}
}
输出结果是什么呢?
第一种:
true
true
第二种:
false
false
其实上面的输出都不对,正确输出是:
true
false
那么为什么会是这种输出结果呢?
我们知道 Integer var0 = 100
这里java编译器自动帮我们把原始类型装箱为Integer类型。来看一下过编译后的代码我们反编译下上面的语句实际执行的是什么。
public static void main(java.lang.String[]);
Code:
0: bipush 100
2: invokestatic #2 // Method java/lang/Integer.valueOf:(I)Ljava/lang/Integer;
5: astore_1
6: bipush 100
8: invokestatic #2 // Method java/lang/Integer.valueOf:(I)Ljava/lang/Integer;
11: astore_2
12: sipush 130
15: invokestatic #2 // Method java/lang/Integer.valueOf:(I)Ljava/lang/Integer;
18: astore_3
19: sipush 130
22: invokestatic #2 // Method java/lang/Integer.valueOf:(I)Ljava/lang/Integer;
25: astore 4
27: getstatic #3 // Field java/lang/System.out:Ljava/io/PrintStream;
30: aload_1
31: aload_2
可以看到
0: bipush 100
2: invokestatic #2 // Method java/lang/Integer.valueOf:(I)Ljava/lang/Integer;
5: astore_1
表明了实际上
Integer var0 = 100;调用的是
Integer var0 = Integer.valueOf(100);这个方法.
在后面,我们分析一下*Integer.valueOf()*这个方法的原理。
类定义
Integer提供了与string,int,long,short,float,double类型转换的方法,以及一些简单的大小比较.
public final class Integer extends Number implements Com
parable<Integer>
final表示Integer是不可变对象(不可变对象是线程安全的), 继承Number类(number类实现了Serializable表示可以被序列化),实现Comparable接口(对象可以比较大小)。
构造器
1.
public Integer(int value) {
this.value = value;
}
初始化Integer的值大小。
2.
public Integer(String s) throws NumberFormatException {
this.value = parseInt(s, 10);
}
使用string类型类构造integer。
属性
1.
public static final int MIN_VALUE = 0x80000000;
Integer最小的值大小-2^31次方
2.
public static final int MAX_VALUE = 0x7fffffff;
Integer最大的值大小2^31次方
3.
private final int value;
包装类存储的整形值。
内部类
在Integer加载过程初始化IntegerCache,默认最大值是127,最小值-128,并且会出实话**cache[]**数组来存储 -128 ~ 127。在valueOf方法中如果在这个返回内,直接从缓存取值,这也是上面的面试题返回true false 的根本原因。
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() { }
}
类方法
1.
整形值转为16进制,相应的还有转为8进制,2进制方法。
public static String toHexString(int i) {
return toUnsignedString0(i, 4);
}
2.
开篇说到的Integer var0 = 100 实际上调用的是这个方法,我们已经在IntegerCache解释了会从缓存中取值。
public static Integer valueOf(int i) {
if (i >= IntegerCache.low && i <= IntegerCache.high)
return IntegerCache.cache[i + (-IntegerCache.low)];
return new Integer(i);
}
##实例方法
1.
public Integer(String s) throws NumberFormatException {
this.value = parseInt(s, 10);
}
2.
字符串转为10进制数字,
radix不能小于2,不能大于36.
在while循环中有一个判断 result < multmin的实际意思不能大于MAX_VALUE 与不能小于MIN_VALUE。
**result *= radix;**的意思每次循环到这里扩大十倍最终会把每一位放到响应的位置。result -= digit 当前个位数的值。
public static int parseInt(String s, int radix)
throws NumberFormatException
{
/* * WARNING: This method may be invoked early during VM initialization * before IntegerCache is initialized. Care must be taken to not use * the valueOf method. */
if (s == null) {
throw new NumberFormatException("null");
}
if (radix < Character.MIN_RADIX) {
throw new NumberFormatException("radix " + radix +
" less than Character.MIN_RADIX");
}
if (radix > Character.MAX_RADIX) {
throw new NumberFormatException("radix " + radix +
" greater than Character.MAX_RADIX");
}
int result = 0;
boolean negative = false;
int i = 0, len = s.length();
int limit = -Integer.MAX_VALUE;
int multmin;
int digit;
if (len > 0) {
char firstChar = s.charAt(0);
if (firstChar < '0') { // Possible leading "+" or "-"
if (firstChar == '-') {
negative = true;
limit = Integer.MIN_VALUE;
} else if (firstChar != '+')
throw NumberFormatException.forInputString(s);
if (len == 1) // Cannot have lone "+" or "-"
throw NumberFormatException.forInputString(s);
i++;
}
multmin = limit / radix;
while (i < len) {
// Accumulating negatively avoids surprises near MAX_VALUE
digit = Character.digit(s.charAt(i++),radix);
if (digit < 0) {
throw NumberFormatException.forInputString(s);
}
if (result < multmin) {
throw NumberFormatException.forInputString(s);
}
result *= radix;
if (result < limit + digit) {
throw NumberFormatException.forInputString(s);
}
result -= digit;
}
} else {
throw NumberFormatException.forInputString(s);
}
return negative ? result : -result;
}
3.
继承自Number方法,强转为byte
public byte byteValue() {
return (byte)value;
}
4.
继承自Number方法,返回属性 value的值。
public int intValue() {
return value;
}
5.
继承自Number方法,强转为long
public long longValue() {
return (long)value;
}
equals() && hashCode()
使用属性value作为hashCode
public int hashCode() {
return Integer.hashCode(value);
}
public static int hashCode(int value) {
return value;
}
重写了Object的equals方法
判断是否是integer是的话比较value属性是否相等。
public boolean equals(Object obj) {
if (obj instanceof Integer) {
return value == ((Integer)obj).intValue();
}
return false;
}
还没有评论,来说两句吧...