Java学习十四天(包装类 Integer类型 一些常用方法)

包装类:

引用包装类的原因“

1)因为Java是面向对象编程的,但是基本数据类型没有对象,为了完善面向对象的编程,所以给基本类型添加了包装类。

2)Java中的集合,只允许存储引用数据类型。

除了Integer类型和Character类型之外,其他的都和基本类型一样,但是首字母大写

包装类体系结构图:

学习Integer类:

查阅API:

它的属性有:

package Integer;

public class IntegerTest {
    public static void main(String[] args) {
        System.out.println("Integer最大值为: "+Integer.MAX_VALUE);
        System.out.println("Integer最小值为: "+Integer.MIN_VALUE);
        System.out.println(Integer.TYPE);
    }
}

 

查看integer的构造方法:

        Integer i2=new Integer(s);
        System.out.println(i2);

打印对象没有显示地址,说明重写了toString方法。

         Integer i=new Integer(123);
         Integer i2=new Integer(123);
        System.out.println(i==i2);//false 说明new的两个是不同的对象,执向两个不同的地址
        System.out.println(i.equals(i2));//true 说明重写了equlas方法,比较了两个值是否相等

Integer>>>><<<<<int>>>><<<<String 之间互相转换

        String string="123";
        int i=123;
//        int>>>>>Integer
        Integer i2=new Integer(3);
//        Integer>>>>>int
          i=i2.intValue();
//          int>>>String
        string=String.valueOf(i);
//        string>>>>int
        i=Integer.parseInt(string);
//        Integer>>>String
        string=String.valueOf(i2);
//        String>>>Integer
        i2=Integer.valueOf(string);

自动装箱:基本类型直接赋值给包装类

自动拆箱:包装类直接赋值给基本数据类型

 

自动装箱是否会在内存里开辟一个空间呢?

        Integer i=127;
        Integer i2=127;
        System.out.println(i==i2);//true
        Integer i3=128;
        Integer i4=128;
        System.out.println(i3==i4);//false
//        自动装箱不开空间的范围是:-128-127,超过了这个值都会重新的开辟一个空间

源码解释:

//Integer中的私有的静态内部类 ,IntegerCache在Integer类第一次被使用时加载到内存,而且只加载一次
private static class IntegerCache { 
        static final int low = -128;
        static final int high;           //声明静态常量high
        static final Integer cache[];    //声明一个Integer类型的数组,数组的名称为cache
                //静态代码块:作用,为类的静态属性赋值
        static {
          
            int h = 127;  
          
            high = h;  //high的值为127
         //cache=new Integer[256]; cache这个数组的长度为256
            cache = new Integer[(high - low) + 1];  
                        
            int j = low;   //j=-128
            for(int k = 0; k < cache.length; k++)
                cache[k] = new Integer(j++);   //cache[0]=new Integer(-128); 
                                                    //...
                                                //cache[255]=new Integer(127);													
        }
        private IntegerCache() {}
    }

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值