【Mark】包装类 19_12_7

包装类

  • 包装类型非常有用
  • 包装类型就是把基本类型包装为class
    public class Integer {
        private int value;
    
        public Integer(int value) {
            this.value = value;
        }
    
        public int intValue() {
            return this.value;
        }
    }

    Auto Boxing(自动装箱)(编译时)

    • 自动拆、装箱只是为了少写代码(不用好一点)
      Integer n1 = Integer.valueOf(99);    //装箱(基本类型封装为包装类)
      int n3 = n1.intValue();        //拆箱(输出值)
      
      Integer n = 100;    //自动装箱,就是少写了Integer.valueOf();
      int x = n;        //自动拆箱,就是少写了intValue();
      • 而且自动拆箱有时会报NullPointException,例如:

  Integer n = null; int x = n;

不变类

  • 即实例对象不变,和 string 的不变是应该是一个道理(自己认为)
  • Java字符串的一个重要特点就是字符串不可变。这种不可变性是通过内部的 private final char[] 字段,以及没有任何修改 char[] 的方法实现的。

  • 所有包装类型都是不变类

    静态工厂方法

    • 返回是一个实例的方法,比如 Integer.valueOf();

      有静态工厂方法的情况下优先用静态工厂方法,而不用 new

Number类

  • 整型、浮点型的包装类都是继承自Number类
  • 向上转型之后

  可以非常方便地转为各种类型 .DataTypeValue();

Number num = Integer.valueOf(99);
int n = num.intValue();
float f = num.floatValue();
//... .DataTypeValue();

数据的存储和显示要分离

  • 就标题这一句话

无符号整数

.toUnsignedInt();

猜你喜欢

转载自www.cnblogs.com/concentrate-haolong/p/12003228.html