首页 > 编程语言 >2.Integer源码解析

2.Integer源码解析

时间:2022-10-24 22:32:42浏览次数:45  
标签:int 源码 static NumberFormatException Integer 解析 public IntegerCache


1.取值范围和基本数据类型
源码

public final class Integer extends Number implements Comparable<Integer> {
//该值用于定义Integer取值的最小值
@Native public static final int MIN_VALUE = 0x80000000;

//该值用于定义Integer取值的最大值
@Native public static final int MAX_VALUE = 0x7fffffff;

//该值用于定义Integer的基本数据类型
@SuppressWarnings("unchecked")
public static final Class<Integer> TYPE = (Class<Integer>) Class.getPrimitiveClass("int");
}

源码解析

  1. Integer是被final修饰的类型,继承Number类并实现Comparable接口。
  2. Integer的最小值为-2^31 ,最大值为2^31-1。
  3. Integer的基本数据类型为int。

2.toString
源码

public final class Integer extends Number implements Comparable<Integer> {
public static String toString(int i) {
if (i == Integer.MIN_VALUE)
return "-2147483648";
//计算整数i的位数
int size = (i < 0) ? stringSize(-i) + 1 : stringSize(i);
char[] buf = new char[size];
/**
* 将代表整数i的字符放入字符数组buf
* 字符从指定索引处的最低有效数字(不包括最高位字符)开始向后放置
*/
getChars(i, size, buf);
return new String(buf, true);
}

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

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

源码解析
计算Integer数的长度时,是通过构建一个一维数组,然后拿该Integer数与数组每个值进行比较。而未使用经常采用的除法来计算长度,这是因为计算机在计算除法效率要比加减乘法低,为了避免除法,提高计算效率,因此采用此种方法。

总结
在计算某个数的长度时,可以参考Integer类的stringSize()方法。

3.IntegerCache
源码

private static class IntegerCache {
static final int low = -128;
static final int high;
static final Integer cache[];

static {
int h = 127;
//缓存的最大值是VM参数里java.lang.Integer.IntegerCache.high这个属性
String integerCacheHighPropValue = sun.misc.VM.getSavedProperty("java.lang.Integer.IntegerCache.high");
if (integerCacheHighPropValue != null) {
try {
int i = parseInt(integerCacheHighPropValue);
i = Math.max(i, 127);
//最大数组大小为Integer.MAX_VALUE
h = Math.min(i, Integer.MAX_VALUE - (-low) - 1);
} catch (NumberFormatException nfe) {
//如果无法将属性解析为int,则忽略它
}
}
high = h;

cache = new Integer[(high - low) + 1];
int j = low;
for (int k = 0; k < cache.length; k++)
cache[k] = new Integer(j++);

assert Integer.IntegerCache.high >= 127;
}

private IntegerCache() {
}
}

源码解析

  1. 初始化Integer后,IntegerCache会缓存[-128,127]之间的数据,这个区间的上限可以配置,取决于java.lang.Integer.IntegerCache.high这个属性,这个属性在VM里可以使用-XX:AutoBoxCacheMax=2000或者-Djava.lang.Integer.IntegerCache.high=2000进行调整。
  2. 在该范围内数据比较常用,添加缓存可以提高性能,不用每次都新建,浪费系统资源。同时根据Integer的hashCode方法,可以看到,Integer的hashCode返回本身的int值。

面试点

//程序1-2
public class App {
public static void main(String[] args) {
Integer a = 1;
Integer b = 1;
Integer c = new Integer(1);
Integer d = 1000;
Integer e = 1000;
System.out.println(a == b);//true
System.out.println(b == c);//false
System.out.println(d == e);//false
}
}

4.valueOf和parseInt
源码

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

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

public static int parseInt(String s, int radix) throws NumberFormatException {
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') {
if (firstChar == '-') {
negative = true;
limit = Integer.MIN_VALUE;
} else if (firstChar != '+')
throw NumberFormatException.forInputString(s);

if (len == 1)
throw NumberFormatException.forInputString(s);
i++;
}
multmin = limit / radix;
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 {
throw NumberFormatException.forInputString(s);
}
return negative ? result : -result;
}
}

源码解析

  1. valueOf方法会从缓存中取值,如果命中缓存,会减少资源的开销。
  2. parseInt方法首先会进行异常处理,然后判断传入的String是否有正负号,截取位数后,使用乘法和减法得到int值,最后判断正负并返回结果。


标签:int,源码,static,NumberFormatException,Integer,解析,public,IntegerCache
From: https://blog.51cto.com/u_15843693/5791487

相关文章

  • 认识 Redis client-output-buffer-limit 参数与源码分析
    概述Redis的​​client-output-buffer-limit​​可以用来强制断开无法足够快从redis服务器端读取数据的客户端。保护机制规则如下:[hardlimit]大小限制,当某一客户端缓......
  • timedatectl解析
    一,timedatectl输出解析root@sonic:/home/admin#timedatectl             Localtime:Mon2022-10-2421:01:56CST           Universalti......
  • WebRTC源码学习02---webrtc源码编译安装(Mac)
    参考文献https://webrtc.org.cn/mirror/ (主要参考文章)https://www.an.rustfisher.com/webrtc/intro/sync-build/(参考一下代理设置)https://blog.csdn.net/dangwei_90/ar......
  • 基于ssm高校科研管理系统-计算机毕业设计源码+LW文档
    【摘要】高校科研管理是一项重要而又繁琐的工作,有效的信息管理平台可以大大缓解科研管理压力,减少工作量。本文以石河子大学信息科学与技术学院为应用背景,开发教师教学信息......
  • 基于ssm工商学院办公用品管理信息系统设计与实现-计算机毕业设计源码+LW文档
    摘 要本高校科研管理系统设计目标是实现高校科研管理的信息化管理,提高管理效率,使得高校科研管理工作规范化、科学化、高效化。本文研究的高校科研管理系统基于SSM架构,采......
  • Vue源码解读之InitState
    前面我们讲到了_init函数的执行流程,简单回顾下:初始化生命周期-initLifecycle初始化事件-initEvents初始化渲染函数-initRender调用钩子函数-beforeCreate初始化依赖......
  • Vue3源码解读之patch
    例子代码本篇将要讲解domdiff,那么咱们结合下面的例子来进行讲解,这个例子是在上一篇文章的基础上,加了一个数据变更,也就是list的值发生了改变。html中增加了一个按钮change......
  • openGemini内核源码正式对外开源
    摘要:openGemini是一个开源的分布式时序数据库系统,可广泛应用于物联网、车联网、运维监控、工业互联网等业务场景,具备卓越的读写性能和高效的数据分析能力。本文分享自华为......
  • SpringCloud系列之网关gateway-2.Gateway体系架构解析
    打开Gateway的自动装配工厂GatewayAutoConfiguration来看一下,排头第一个类就是Netty。Netty是什么?在网络传输领域Netty就是身份的象征,黄金AK般的存在,它是非阻塞、高性能、高......
  • java类uuid源码分析
    通用唯一识别码(英语:UniversallyUniqueIdentifier,简称UUID)是一种软件建构的标准,亦为自由软件基金会组织在分散式计算环境领域的一部份。UUID的目的,是让分散式系统中的所有......