包装类&自定义包装类

包装类

  • 除了int和char是Integer和Character之外其他都是首字母大写

在这里插入图片描述

  • Number类:除了Character和Boolean之外的都是“数字型”,都是Number的子类
  • Number类是抽象类他的方法子类都实现,它的子类之间可以互相转换
  • ,

包装类作用

  • 可以把基本数据字符串包装类对象之间来回转化
  • 作为和基本数据类型对应的类型存在,方便涉及到对象的操作,如 Object[ ]、集合等的操作。
package com.ssc.someclass;

public class Packaging {

	public static void main(String[] args) {
		// TODO Auto-generated method stub
		//基本数据类型转为对象
		Integer i = Integer.valueOf(10);
		
		//包装类对象转化为基本数据类型
		double d = i.doubleValue();
		
		//字符串转为Integer对象
		Integer i1 = Integer.valueOf("234");
		Integer i2 = Integer.parseInt("234");
		
		//包装类转换为字符串
		String str = i2.toString();
		
		//一些常用的常量
		System.out.println(Integer.MAX_VALUE);
		System.out.println(Integer.MIN_VALUE);
	}

}

自动拆箱和装箱&包装类缓存问题&空指针问题

  • 自动拆箱是通过xxxValue()实现的
  • 自动装箱是通过valueOf()实现的
  • 空指针:null 表示 i 没有指向任何对象的实体,但作为对象名称是合法的由于实际上 i 并没有指向任何对象的实体,所以也就不可能操作 intValue()方法,这样上面的写法在运行时就会出现 NullPointerException 错误
		//自动装箱
		Integer a = 5; //编译器直接帮助我们完成	Integer a = Integer.valueOf(5); 
		
		//自动拆箱
		int b = a;//编译器直接帮助我们完成	a.intValue();
		
		//空指针
//		Integer c = null;
//		int c2 = c;

		//包装类的缓存问题
		Integer d1 = 4000;
		Integer d2 = 4000;
		
		//当数字在-128-127之间时返回缓存数组中的某个元素
		Integer d3 = 123;
		Integer d4 = 123;
		System.out.println(d1==d2);//false
		System.out.println(d3==d4);//true
		System.out.println(d1.equals(d2));//true

自定义一个包装类

package com.ssc.someclass;

public class MyInteger {
	private int value=300;
	private static MyInteger[] cache = new MyInteger[256];
	public final static int LOW = -128;
	public final static int HIGH = 127;
	static {
		for(int i=MyInteger.LOW;i<=HIGH;i++) {
			cache[i+128] = new MyInteger(i);
		}
	}
	
	public static MyInteger valueOf(int i) {
		if(i>=LOW && i<HIGH) {
			return cache[i+128];
		}
		return new MyInteger(i);
	}
	private MyInteger(int i) {
		this.value = i;
	}
	@Override
	public String toString() {
		// TODO Auto-generated method stub
		return this.value+"";
	}
	
	public static void main(String[] args) {
		// TODO Auto-generated method stub
		MyInteger m = MyInteger.valueOf(40);
		System.out.println(m);
	}
}


  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值