数据类型
来源:互联网 发布:通达信日线数据 编辑:程序博客网 时间:2024/06/07 07:32
数据类型
Java的数据类型划分
- 基本类型
- 整型
- byte (包装类型:Byte)
- short (包装类型:Short)
- int (包装类型:Integer)
- long(包装类型:Long)
- char(包装类型:Character)
- 浮点型
- float (包装类型:Float)
- double (包装类型:Double)
- 布尔型
- boolean (包装类型:Boolean)
- 整型
- 引用类型
- 类
- 接口
- 数组
- 字符串
- String
自动装箱和拆箱
自从jdk1.5起,就支持自动包装和拆箱。
以int为例:int的包装类型是Integer。
自动包装
看下面的代码:
Integer i = 1;Integer是一个类,他获取实例,应该使用关键字new,例如:
Integer i= new Integer(1);那么Integer i = 1这样写问什么可以?这是因为Integer的valueOf这个方法把1包装成new Integer(1)。我们来看看它是怎样包装的。
public static Integer valueOf(int i) { assert IntegerCache.high >= 127; if (i >= IntegerCache.low && i <= IntegerCache.high) return IntegerCache.cache[i + (-IntegerCache.low)]; return new Integer(i); }
从上面的代码可以看到如果 i小于IntegerCache.low或者 i大于IntegerCache.high直接new一个Integer。那么IntegerCache.low和IntegerCache.high是多少?下面是IntegerCache类的代码:
private static class IntegerCache { static final int low = -128; static final int high; static final Integer cache[]; static { int h = 127; //从缓存中获取high值,当还没有缓存时,这个值为null String integerCacheHighPropValue = sun.misc.VM.getSavedProperty("java.lang.Integer.IntegerCache.high"); if (integerCacheHighPropValue != null) { 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); } //一般来说high=127 high = h; cache = new Integer[(high - low) + 1]; int j = low; for(int k = 0; k < cache.length; k++) cache[k] = new Integer(j++); } private IntegerCache() {} }
从上面的代码可以看到IntegerCache.low=-128,IntegerCache.high=127。回到valueOf这个方法上,注意到 IntegerCache.cache[i + (-IntegerCache.low)], i+128作为数组的索引,而不是值。这就解释了为什么会出现下面这种情况。
阅读全文
0 0
- 数据类型
- 数据类型
- 数据类型
- 数据类型
- 数据类型
- 数据类型
- 数据类型
- 数据类型
- 数据类型
- 数据类型
- 数据类型
- 数据类型
- 数据类型
- 数据类型
- 数据类型
- 数据类型
- 数据类型
- 数据类型
- 期刊影响因子查询
- Spring的IoC容器实现
- 第14章 高级I/O函数
- python3 使用决策树进行分类
- 理解dojo.require机制
- 数据类型
- 数据结构实验项目三:队列的基本操作应用
- Leetcode二分查找算法
- An Easy Problem?! POJ 2826 计算几何
- ubuntu快速安装实现keepalived的主备切换
- augular之通讯HttpClient
- Percona XtraBackup 完全及增量备份与恢复的方法
- 求水仙花数
- C++得到函数执行所用时间