叫我俗先生

V1

2022/10/08阅读:19主题:蔷薇紫

Java学习笔记HSP之包装类

b站视频课程链接-韩顺平Java讲解

本小节笔记从第460集包装类开始,此后将进行Java的一些标准类库的学习与使用。

包装类

  • 包装类是指将Java中的八大基本数据类型加一封装而得到的类。
    8种基本数据类型及对应包装类型表 查看基本数据类型占用字节数可以使用 对应的包装类.SIZE 查看, 它返回bit数 例如 Integer.SIZE = 32;
基本数据类型 占用字节数 对应包装类
boolean Undefined Boolean
byte 1 Byte
short 2 Short
char 2 Character
int 4 Integer
float 4 Float
long 8 Long
double 8 Double
  • 类间的继承实现关系图示例

  • 包装类与基本类型的转换:装箱与拆箱 以intInteger为例, jdk5以后, 可以互相直接赋值(自动)

static void test02Boxes(){
        int a = 5, b = 5;
        // 1. 手动 new 一个
        Integer ia = new Integer(a);
        // 2. 使用 valueOf() 方法
        Integer ib = Integer.valueOf(b);
        System.out.println(ia == ib);
        // 3. 自动的
        Integer ic = a;
        System.out.println(ic == ib);
        // unboxing
        int c = ic;
        int d = ic.intValue();
        System.out.println(c == d);  
}
// false true true
// 将a和b的值改为 a = b = 128
// false false true
// 关键在于valueOf的实现
public static Integer valueOf(int i) {
  if (i >= IntegerCache.low && i <= IntegerCache.high)
    return IntegerCache.cache[i + (-IntegerCache.low)];
  return new Integer(i);
}

Integer与三元运算符与if-else

static void test03Triple(){
  Object object = true?new Integer(1): new Double(2);
  System.out.println(object);
  Object object2;
  if(true){
      object2 = new Integer(1);
  }else {
      object2 = new Double(2);
  }
  System.out.println(object2);
}
// 1.0 1
  • Integer和String之间的转换
    static void test04StrInt(){
        Integer integer = 2;
        // 1. i -> str
        String s1 = integer+"";
        String s2 = integer.toString();
        String s3 = String.valueOf(integer);
        // 2. str -> integer
        integer = Integer.valueOf(s1);
        integer = Integer.parseInt(s2); // 隐式使用了自动 boxing
        integer = new Integer(s3);
    }
  • Character 类、Integer 类的一些方法实例:
public class CharacterMethod {
    public static void main(String[] args){
        // 本方法展示Character类的诸多用法
        System.out.println(Integer.MAX_VALUE);
        System.out.println(Integer.MIN_VALUE);
        System.out.println(Character.isDigit('1'));
        System.out.println(Character.isLetter('('));
        System.out.println(Character.isUpperCase('a'));
        System.out.println(Character.isLowerCase('a'));
        System.out.println(Character.isWhitespace('\t'));
        System.out.println(Character.toUpperCase('a'));
        System.out.println(Character.toLowerCase('A'));
    }
}

2022年9月19日

String

  • String的基本概念与构造方法
  • String使用的细节
  • 两种常见的创建String方法的底层实现差异比较 练习 练习2 细节2 debug and step into ! 练习 练习2

String常用方法

  • String类使用场景缺陷
  • String常用方法

分类:

后端

标签:

Java

作者介绍

叫我俗先生
V1