概述
JAVA给简单类型都提供了对应的类类型(包装类型)
byte Byte
char Character
short Short
int Integer
long Long
float Float
double Double
boolean Boolean
void Void
总结:
- int 和Integer在进行比较的时候,Integer会进行拆箱,转为int值与int进行比较。
- Integer与Integer比较的时候,由于直接赋值的时候会进行自动的装箱,需要注意两个问题,一个是-128<= x<=127的整数,将会直接缓存在IntegerCache中,当赋值在这个区间的时候,不会创建新的Integer对象,而是从缓存中获取已经创建好的Integer对象。二是当大于这个范围的时候,直接new Integer来创建Integer对象。
例如:
new Integer(1) 和Integer a = 1不同,前者会创建对象,存储在堆中,而后者因为在-128到127的范围内,不会创建新的对象,而是从IntegerCache中获取的。那么Integer a = 128, 大于该范围的话才会直接通过new Integer(128)创建对象,进行装箱。
Integer中的装箱的代码
public static Integer valueOf(int i){
if(i>=IntegerCache.low && i<=IntegerCache.high){
return IntegerCache.cache[i+(-IntegerCache.low)];
}
return new Integer(i);
}
代码测试:
package com.example;
public class MainTestDemo {
public static void main(String[] args) {
//简单类型定义的变量,内存都在函数栈上
//引用变量都在函数栈上存储,但是存储的只是对象的引用(堆上的地址)
Integer int1=10; //栈上
Integer int2=new Integer(10); //堆上
if(int1==int2){
System.out.println("int1==int2");
}else{
System.out.println("int1!=int2");
}
Integer int3=new Integer(10); //new的时候在堆中重新分配存储空间,int2和int3存储的堆上的地址不一样
if(int2==int3){
System.out.println("int2==int3");
}else{
System.out.println("int2!=int3");
}
Integer int4=new Integer(200); //分配的地址不同
Integer int5=new Integer(200);
if(int4==int5){
System.out.println("int4==int5");
}else{
System.out.println("int4!=int5");
}
Integer int6=127;
Integer int7=127;//Integer int7=int6;
if(int6==int7){
System.out.println("int6==int7");
}else{
System.out.println("int6!=int7");
}
//i6、i7是自动装箱产生的对象,其值都是127,127正好在-128<=i7<=127
//这个范围内的,那么会去IntegerCache中取,该对象应该是一个对象,在堆中的
//地址应该是一样的,所以在判断两个对象是不是==的时候,会输出相等。
Integer int8=128;
Integer int9=128;
if(int8==int9){
System.out.println("int8==int9");
}else{
System.out.println("int8!=int9");
}
//i8和i9是自动装箱产生的Integer的对象,但是其大小超过了范围:-128<=A <=127,
//这里会直接自己创建该对象即:new Integer(128);显然这两个对象都是new出来,
//在堆中的地址值是不同的,所以二者不相等。
}
}
注:
Byte、Float、Double没有缓存;
Integer、Short、Long的缓存范围都是[-128,127];
Character的缓存范围是[0,127].
最后
以上就是忧心大山为你收集整理的java——装包与拆包的全部内容,希望文章能够帮你解决java——装包与拆包所遇到的程序开发问题。
如果觉得靠谱客网站的内容还不错,欢迎将靠谱客网站推荐给程序员好友。
本图文内容来源于网友提供,作为学习参考使用,或来自网络收集整理,版权属于原作者所有。
发表评论 取消回复