首页 > 编程语言 >java的Integer类源码详解

java的Integer类源码详解

时间:2023-02-23 23:06:38浏览次数:36  
标签:radix java int return 源码 static Integer public


java的Integer类源码详解

类的定义

public final class Integer extends Number implements Comparable<Integer> {
@Native public static final int MIN_VALUE = 0x80000000;

@Native public static final int MAX_VALUE = 0x7fffffff;

@SuppressWarnings("unchecked")
public static final Class<Integer> TYPE = (Class<Integer>) Class.getPrimitiveClass("int");

final static char[] digits = {
'0' , '1' , '2' , '3' , '4' , '5' ,
'6' , '7' , '8' , '9' , 'a' , 'b' ,
'c' , 'd' , 'e' , 'f' , 'g' , 'h' ,
'i' , 'j' , 'k' , 'l' , 'm' , 'n' ,
'o' , 'p' , 'q' , 'r' , 's' , 't' ,
'u' , 'v' , 'w' , 'x' , 'y' , 'z'
};

public String toString() {
return toString(value);
}

public static String toString(int i) {
if (i == Integer.MIN_VALUE)
return "-2147483648";
int size = (i < 0) ? stringSize(-i) + 1 : stringSize(i);
char[] buf = new char[size];
getChars(i, size, buf);
return new String(buf, true);
}

public static String toString(int i, int radix) {
if (radix < Character.MIN_RADIX || radix > Character.MAX_RADIX)
radix = 10;

/* Use the faster version */
if (radix == 10) {
return toString(i);
}

char buf[] = new char[33];
boolean negative = (i < 0);
int charPos = 32;

if (!negative) {
i = -i;
}

while (i <= -radix) {
buf[charPos--] = digits[-(i % radix)];
i = i / radix;
}
buf[charPos] = digits[-i];

if (negative) {
buf[--charPos] = '-';
}

return new String(buf, charPos, (33 - charPos));
}

static void getChars(int i, int index, char[] buf) {
int q, r;
int charPos = index;
char sign = 0;

if (i < 0) {
sign = '-';
i = -i;
}

// Generate two digits per iteration
while (i >= 65536) {
q = i / 100;
// really: r = i - (q * 100);
r = i - ((q << 6) + (q << 5) + (q << 2));
i = q;
buf [--charPos] = DigitOnes[r];
buf [--charPos] = DigitTens[r];
}

// Fall thru to fast mode for smaller numbers
// assert(i <= 65536, i);
for (;;) {
q = (i * 52429) >>> (16+3);
r = i - ((q << 3) + (q << 1)); // r = i-(q*10) ...
buf [--charPos] = digits [r];
i = q;
if (i == 0) break;
}
if (sign != 0) {
buf [--charPos] = sign;
}
}

final static int [] sizeTable = { 9, 99, 999, 9999, 99999, 999999, 9999999,
99999999, 999999999, Integer.MAX_VALUE };

// Requires positive x
static int stringSize(int x) {
for (int i=0; ; i++)
if (x <= sizeTable[i])
return i+1;
}

public static String toUnsignedString(int i, int radix) {
return Long.toUnsignedString(toUnsignedLong(i), radix);
}

public static String toHexString(int i) {
return toUnsignedString0(i, 4);
}

public static String toOctalString(int i) {
return toUnsignedString0(i, 3);
}

public static String toBinaryString(int i) {
return toUnsignedString0(i, 1);
}

private static String toUnsignedString0(int val, int shift) {
// assert shift > 0 && shift <=5 : "Illegal shift value";
int mag = Integer.SIZE - Integer.numberOfLeadingZeros(val);
int chars = Math.max(((mag + (shift - 1)) / shift), 1);
char[] buf = new char[chars];

formatUnsignedInt(val, shift, buf, 0, chars);

// Use special constructor which takes over "buf".
return new String(buf, true);
}

static int formatUnsignedInt(int val, int shift, char[] buf, int offset, int len) {
int charPos = len;
int radix = 1 << shift;
int mask = radix - 1;
do {
buf[offset + --charPos] = Integer.digits[val & mask];
val >>>= shift;
} while (val != 0 && charPos > 0);

return charPos;
}
}

nteger 是用 final 声明的常量类,不能被任何类所继承。并且 Integer 类继承了 Number 类和实现了 Comparable 接口。 Number 类是一个抽象类,8中基本数据类型的包装类除了Character 和 Boolean 没有继承该类外,剩下的都继承了 Number 类,该类的方法用于各种数据类型的转换,Comparable 接口就一个  compareTo 方法,用于元素之间的大小比较。

java的Integer类源码详解_java的Integer类源码详解

  int 类型在 Java 中是占据 4 个字节,所以其可以表示大小的范围是 -2 31——2 31 -1即 -2147483648——2147483647,我们在用 int 表示数值时一定不要超出这个范围了。

    toString三个方法重载,能返回一个整型数据所表示的字符串形式,其中最后一个方法 toString(int,int) 第二个参数是表示的进制数。

 toString(int) 方法内部调用了 stringSize() 和 getChars() 方法,stringSize() 它是用来计算参数 i 的位数也就是转成字符串之后的字符串的长度,内部结合一个已经初始化好的int类型的数组sizeTable来完成这个计算。

  实现的形式很巧妙。注意负数包含符号位,所以对于负数的位数是 stringSize(-i) + 1。

       getChars(int i,int index,char[] buf)

     i:被初始化的数字,

  index:这个数字的长度(包含了负数的符号“-”)

  buf:字符串的容器-一个char型数组。

  第一个if判断,如果i<0,sign记下它的符号“-”,同时将i转成整数。下面所有的操作也就只针对整数了,最后在判断sign如果不等于零将 sign 你的值放在char数组的首位buf [--charPos] = sign;。  

private final int value;

public Integer(int value) {
this.value = value;
}

public Integer(String s) throws NumberFormatException {
this.value = parseInt(s, 10);
}

public static Integer valueOf(int i) {
if (i >= IntegerCache.low && i <= IntegerCache.high)
return IntegerCache.cache[i + (-IntegerCache.low)];
return new Integer(i);
}

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() {}
}

public byte byteValue() {
return (byte)value;
}

public short shortValue() {
return (short)value;
}

public int intValue() {
return value;
}

public long longValue() {
return (long)value;
}

public float floatValue() {
return (float)value;
}

public double doubleValue() {
return (double)value;
}

public static int parseInt(String s) throws NumberFormatException {
return parseInt(s,10);
}

public static int parseInt(String s, int radix) throws NumberFormatException{
//如果转换的字符串如果为null,直接抛出空指针异常
if (s == null) {
throw new NumberFormatException("null");
}
//如果转换的radix(默认是10)<2 则抛出数字格式异常,因为进制最小是 2 进制
if (radix < Character.MIN_RADIX) {
throw new NumberFormatException("radix " + radix +
" less than Character.MIN_RADIX");
}
//如果转换的radix(默认是10)>36 则抛出数字格式异常,因为0到9一共10位,a到z一共26位,所以一共36位
//也就是最高只能有36进制数
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();//len是待转换字符串的长度
int limit = -Integer.MAX_VALUE;//limit = -2147483647
int multmin;
int digit;
//如果待转换字符串长度大于 0
if (len > 0) {
char firstChar = s.charAt(0);//获取待转换字符串的第一个字符
//这里主要用来判断第一个字符是"+"或者"-",因为这两个字符的 ASCII码都小于字符'0'
if (firstChar < '0') {
if (firstChar == '-') {//如果第一个字符是'-'
negative = true;
limit = Integer.MIN_VALUE;
} else if (firstChar != '+')//如果第一个字符是不是 '+',直接抛出异常
throw NumberFormatException.forInputString(s);

if (len == 1) //待转换字符长度是1,不能是单独的"+"或者"-",否则抛出异常
throw NumberFormatException.forInputString(s);
i++;
}
multmin = limit / radix;
//通过不断循环,将字符串除掉第一个字符之后,根据进制不断相乘在相加得到一个正整数
//比如 parseInt("2abc",16) = 2*16的3次方+10*16的2次方+11*16+12*1
//parseInt("123",10) = 1*10的2次方+2*10+3*1
while (i < len) {
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 {//如果待转换字符串长度小于等于0,直接抛出异常
throw NumberFormatException.forInputString(s);
}
//根据第一个字符得到的正负号,在结果前面加上符号
return negative ? result : -result;
}

构造方法 Integer(String) 就是将我们输入的字符串数据转换成整型数据。

首先我们必须要知道能转换成整数的字符串必须分为两个部分:第一位必须是"+"或者"-",剩下的必须是 0-9 和 a-z 字符

parseInt(String s)前面通过 toString(int i) 可以将整型数据转换成字符串类型输出,这里通过 parseInt(String s) 能将字符串转换成整型输出。

自动拆箱和装箱

  自动拆箱和自动装箱是 JDK1.5 以后才有的功能,也就是java当中众多的语法糖之一,它的执行是在编译期,会根据代码的语法,在生成class文件的时候,决定是否进行拆箱和装箱动作。


  ①、自动装箱

  我们知道一般创建一个类的对象需要通过 new 关键字,比如:

Object obj = new Object();

  但是实际上,对于 Integer 类,我们却可以直接这样使用:

Integer a = 128;

  为什么可以这样,通过反编译工具,我们可以看到,生成的class文件是:

Integer a = Integer.valueOf(128);

  其实最后返回的也是通过new Integer() 产生的对象,但是这里要注意前面的一段代码,当i的值 -128 <= i <= 127 返回的是缓存类中的对象,并没有重新创建一个新的对象,这在通过 equals 进行比较的时候我们要注意。

  这就是基本数据类型的自动装箱,128是基本数据类型,然后被解析成Integer类。


  ②、自动拆箱

  我们将 Integer 类表示的数据赋值给基本数据类型int,就执行了自动拆箱。

Integer a = new Integer(128);
int m = a;

  反编译生成的class文件:

Integer a = new Integer(128);
int m = a.intValue();

  简单来讲:自动装箱就是Integer.valueOf(int i);自动拆箱就是 i.intValue();

关于缓存类

public static void main(String[] args) {
Integer i = 10;
Integer j = 10;
System.out.println(i == j);

Integer a = 128;
Integer b = 128;
System.out.println(a == b);

int k = 10;
System.out.println(k == i);
int kk = 128;
System.out.println(kk == a);

Integer m = new Integer(10);
Integer n = new Integer(10);
System.out.println(m == n);
}

 答案是:

java的Integer类源码详解_进制_02

  

 ①、Integer 是 int 包装类,int 是八大基本数据类型之一(byte,char,short,int,long,float,double,boolean)

 ②、Integer 是类,默认值为null,int是基本数据类型,默认值为0;

 ③、Integer 表示的是对象,用一个引用指向这个对象,而int是基本数据类型,直接存储数值。

 首先,直接声明Integer i = 10,会自动装箱变为Integer i = Integer.valueOf(10);Integer i 会自动拆箱为 i.intValue()。

  ①、第一个打印结果为 true

  对于 i == j ,我们知道这是两个Integer类,他们比较应该是用equals,这里用==比较的是地址,那么结果肯定为false,但是实际上结果为true。

  分析源码我们可以知道在 i >= -128 并且 i <= 127 的时候,第一次声明会将 i 的值放入缓存中,第二次直接取缓存里面的数据,而不是重新创建一个Ingeter 对象。那么第一个打印结果因为 i = 10 在缓存表示范围内,所以为 true。

  ②、第二个打印结果为 false

  从上面的分析我们知道,128是不在-128到127之间的,所以第一次创建对象的时候没有缓存,第二次创建了一个新的Integer对象。故打印结果为false

  ③、第三个打印结果为 true

  Integer 的自动拆箱功能,也就是比较两个基本数据类型,结果当然为true

  ④、第四个打印结果为 true

  解释和第三个一样。int和integer(无论new否)比,都为true,因为会把Integer自动拆箱为int再去比较。

  ⑤、第五个打印结果为 false

  因为这个虽然值为10,但是我们都是通过 new 关键字来创建的两个对象,是不存在缓存的概念的。两个用new关键字创建的对象用 == 进行比较,结果当然为 false。

Integer a = 1;
Integer b = 2;
Integer c = 3;
Integer d = 3;

Integer e = 321;
Integer f = 321;

Long g = 3L;
Long h = 2L;

System.out.println(c == d);
System.out.println(e == f);
System.out.println(c == (a + b));
System.out.println(c.equals((a+b)));
System.out.println(g == (a+b));
System.out.println(g.equals(a+b));
System.out.println(g.equals(a+h));

 反编译结果:

java的Integer类源码详解_java的Integer类源码详解_03

  打印结果为:

true
false
true
true
true
false
true

  分析:第一个和第二个结果没什么疑问,Integer类在-128到127的缓存问题;

  第三个由于  a+b包含了算术运算,因此会触发自动拆箱过程(会调用intValue方法),==比较符又将左边的自动拆箱,因此它们比较的是数值是否相等。

  第四个对于c.equals(a+b)会先触发自动拆箱过程,再触发自动装箱过程,也就是说a+b,会先各自调用intValue方法,得到了加法运算后的数值之后,便调用Integer.valueOf方法,再进行equals比较。

  第五个对于 g == (a+b),首先计算 a+b,也是先调用各自的intValue方法,得到数值之后,由于前面的g是Long类型的,也会自动拆箱为long,==运算符能将隐含的将小范围的数据类型转换为大范围的数据类型,也就是int会被转换成long类型,两个long类型的数值进行比较。

  第六个对于 g.equals(a+b),同理a+b会先自动拆箱,然后将结果自动装箱,需要说明的是 equals 运算符不会进行类型转换。所以是Long.equals(Integer),结果当然是false

  第七个对于g.equals(a+h),运算符+会进行类型转换,a+h各自拆箱之后是int+long,结果是long,然后long进行自动装箱为Long,两个Long进行equals判断。

@Override
public int hashCode() {
return Integer.hashCode(value);
}

public static int hashCode(int value) {
return value;
}

public boolean equals(Object obj) {
if (obj instanceof Integer) {
return value == ((Integer)obj).intValue();
}
return false;
}

public static Integer getInteger(String nm) {
return getInteger(nm, null);
}

public static Integer getInteger(String nm, int val) {
Integer result = getInteger(nm, null);
return (result == null) ? Integer.valueOf(val) : result;
}

public static Integer getInteger(String nm, Integer val) {
String v = null;
try {
v = System.getProperty(nm);
} catch (IllegalArgumentException | NullPointerException e) {
}
if (v != null) {
try {
return Integer.decode(v);
} catch (NumberFormatException e) {
}
}
return val;
}

public static Integer decode(String nm) throws NumberFormatException {
int radix = 10;
int index = 0;
boolean negative = false;
Integer result;

if (nm.length() == 0)
throw new NumberFormatException("Zero length string");
char firstChar = nm.charAt(0);
// Handle sign, if present
if (firstChar == '-') {
negative = true;
index++;
} else if (firstChar == '+')
index++;

// Handle radix specifier, if present
if (nm.startsWith("0x", index) || nm.startsWith("0X", index)) {
index += 2;
radix = 16;
}
else if (nm.startsWith("#", index)) {
index ++;
radix = 16;
}
else if (nm.startsWith("0", index) && nm.length() > 1 + index) {
index ++;
radix = 8;
}

if (nm.startsWith("-", index) || nm.startsWith("+", index))
throw new NumberFormatException("Sign character in wrong position");

try {
result = Integer.valueOf(nm.substring(index), radix);
result = negative ? Integer.valueOf(-result.intValue()) : result;
} catch (NumberFormatException e) {
// If number is Integer.MIN_VALUE, we'll end up here. The next line
// handles this case, and causes any genuine format error to be
// rethrown.
String constant = negative ? ("-" + nm.substring(index))
: nm.substring(index);
result = Integer.valueOf(constant, radix);
}
return result;
}

public int compareTo(Integer anotherInteger) {
return compare(this.value, anotherInteger.value);
}

public static int compare(int x, int y) {
return (x < y) ? -1 : ((x == y) ? 0 : 1);
}

public static int compareUnsigned(int x, int y) {
return compare(x + MIN_VALUE, y + MIN_VALUE);
}

public static long toUnsignedLong(int x) {
return ((long) x) & 0xffffffffL;
}

public static int divideUnsigned(int dividend, int divisor) {
// In lieu of tricky code, for now just use long arithmetic.
return (int)(toUnsignedLong(dividend) / toUnsignedLong(divisor));
}

public static int remainderUnsigned(int dividend, int divisor) {
// In lieu of tricky code, for now just use long arithmetic.
return (int)(toUnsignedLong(dividend) % toUnsignedLong(divisor));
}


// Bit twiddling
@Native public static final int SIZE = 32;

public static final int BYTES = SIZE / Byte.SIZE;

public static int highestOneBit(int i) {
// HD, Figure 3-1
i |= (i >> 1);
i |= (i >> 2);
i |= (i >> 4);
i |= (i >> 8);
i |= (i >> 16);
return i - (i >>> 1);
}

public static int lowestOneBit(int i) {
// HD, Section 2-1
return i & -i;
}

public static int numberOfLeadingZeros(int i) {
// HD, Figure 5-6
if (i == 0)
return 32;
int n = 1;
if (i >>> 16 == 0) { n += 16; i <<= 16; }
if (i >>> 24 == 0) { n += 8; i <<= 8; }
if (i >>> 28 == 0) { n += 4; i <<= 4; }
if (i >>> 30 == 0) { n += 2; i <<= 2; }
n -= i >>> 31;
return n;
}

public static int numberOfTrailingZeros(int i) {
// HD, Figure 5-14
int y;
if (i == 0) return 32;
int n = 31;
y = i <<16; if (y != 0) { n = n -16; i = y; }
y = i << 8; if (y != 0) { n = n - 8; i = y; }
y = i << 4; if (y != 0) { n = n - 4; i = y; }
y = i << 2; if (y != 0) { n = n - 2; i = y; }
return n - ((i << 1) >>> 31);
}

public static int bitCount(int i) {
// HD, Figure 5-2
i = i - ((i >>> 1) & 0x55555555);
i = (i & 0x33333333) + ((i >>> 2) & 0x33333333);
i = (i + (i >>> 4)) & 0x0f0f0f0f;
i = i + (i >>> 8);
i = i + (i >>> 16);
return i & 0x3f;
}

public static int rotateLeft(int i, int distance) {
return (i << distance) | (i >>> -distance);
}

public static int rotateRight(int i, int distance) {
return (i >>> distance) | (i << -distance);
}

public static int reverse(int i) {
// HD, Figure 7-1
i = (i & 0x55555555) << 1 | (i >>> 1) & 0x55555555;
i = (i & 0x33333333) << 2 | (i >>> 2) & 0x33333333;
i = (i & 0x0f0f0f0f) << 4 | (i >>> 4) & 0x0f0f0f0f;
i = (i << 24) | ((i & 0xff00) << 8) |
((i >>> 8) & 0xff00) | (i >>> 24);
return i;
}

public static int signum(int i) {
// HD, Section 2-7
return (i >> 31) | (-i >>> 31);
}

public static int reverseBytes(int i) {
return ((i >>> 24) ) |
((i >> 8) & 0xFF00) |
((i << 8) & 0xFF0000) |
((i << 24));
}

public static int sum(int a, int b) {
return a + b;
}

public static int max(int a, int b) {
return Math.max(a, b);
}

public static int min(int a, int b) {
return Math.min(a, b);
}

/** use serialVersionUID from JDK 1.0.2 for interoperability */
@Native private static final long serialVersionUID = 1360826667806852920L;
}

equals(Object obj)方法,这个方法很简单,先通过instanceof关键字判断两个比较对象的关系,然后将对象强转为 Integer,在通过自动拆箱,转换成两个基本数据类 int,然后通过 == 比较。

hashCode(),Integer 类的hashCode 方法也比较简单,直接返回其 int 类型的数据。

compareTo(int x,int y)

 如果 x < y 返回 -1

 如果 x == y 返回 0

 如果 x > y 返回 1

System.out.println(Integer.compare(1, 2));//-1
System.out.println(Integer.compare(1, 1));//0
System.out.println(Integer.compare(1, 0));//1

  那么基本上 Integer 类的主要方法就介绍这么多了,后面如果有比较重要的,会再进行更新。

 

标签:radix,java,int,return,源码,static,Integer,public
From: https://blog.51cto.com/u_11837698/6081993

相关文章

  • JavaScript 如何验证 URL
    前言当开发者需要为不同目的以不同形式处理URL时,比如说浏览器历史导航,锚点目标,查询参数等等,我们经常会借助于JavaScript。然而,它的频繁使用促使攻击者利用其漏洞。这种被......
  • Java核心技术读书笔记-输入与输出
    IO流InputStream与OutputStream设计的目的是处理字节流的数据;而Reader和Writer是专门用于处理Unicode字符的类层次结构。read和write方法在执行时都将阻塞,直至字节确实......
  • java的一个小demo
    publicstaticvoidmain(String[]args){intnum=0;num=num++;System.out.println(num);//0num=++num;Sys......
  • java日期类Date与DateFormat源码详解
    java日期类Date与DateFormat源码详解Date类的定义publicclassDateimplementsjava.io.Serializable,Cloneable,Comparable<Date>{privatestaticfinalBaseCal......
  • java的DateFormat、SimpleDateFormate类源码的详解
    java的DateFormat、SimpleDateFormate类源码的详解抽象类Format的定义publicabstractclassFormatimplementsSerializable,Cloneable{privatestaticfinallong......
  • java的NumberFormat、DecimalFormat、MessageFormat类源码详解
    java的NumberFormat、DecimalFormat、MessageFormat类源码详解NumberFormat类的定义publicabstractclassNumberFormatextendsFormat{protectedNumberFormat(){......
  • Jenkins 添加节点 java web方式
    启用代理端口可以自己指定添加节点参数说明:Name(名称):即节点名称Description(描述):介绍该节点的作用,如Docker构建ofexecutors(并发构建数):定义该节点可以执行多少......
  • 深入学习jquery源码之each()
    $.each()遍历一个数组或对象,可以是DOM、json等格式,等价于for循环返回值:jQuery.each(callback) 参数:对于每个匹配的元素所要执行的函数概述:以每一个匹配的元素作为上下文......
  • 深入学习jquery源码之trigger()与triggerHandler()
    深入学习jquery源码之trigger()与triggerHandler()trigger(type,[data])概述:在每一个匹配的元素上触发某类事件。这个函数也会导致浏览器同名的默认行为的执行。比如,如果用......
  • 深入学习jquery源码之map()
    概述将一组元素转换成其他数组(不论是否是元素数组)你可以用这个函数来建立一个列表,不论是值、属性还是CSS样式,或者其他特别形式。这都可以用'$.map()'来方便的建立。参数call......