JavaSE-14
一.基本类型包装类
1.概念:把 8 种基本数据类型,封装成对应的 Java 类,让基本类型变成对象,这个类就叫包装类。
2.Integer包装类
- 静态成员变量
static int MAX_VALUE值为 231-1 的常量,它表示 int 类型能够表示的最大值。
static int MIN_VALUE值为 -231 的常量,它表示 int 类型能够表示的最小值。
- 成员方法
public static Integer valueOf(int i):将基本类型转成Integer对象
public int intValue():返回Integer对象中包含的int值
public static int parseInt(String s):将String的整数转成int类型整数
示例:
public static void main(String[] args) {
Integer in = Integer.valueOf(1);//把基本类型int值1,转为Integer包装类对象
System.out.println(in);//打印Integer对象,自动调用toString(),转为字符串形式输出
System.out.println(in.intValue());//将Integer包装类对象,取出里面的int基本类型值
int i = Integer.parseInt("1");//将字符串"1",解析转换成int基本类型数据
System.out.println(i);
}
3.自动装箱拆箱public static void main(String[] args) {
System.out.println(age);// 装箱 Integer age = 18,底层执行Integer.valueOf(18)
System.out.println(a);// 拆箱 int a = age,底层执行a.intValue()
}
4.自动装箱缓存机制
public static void main(String[] args) {
//-128~127 之间,底层会从一个缓存数组,Integer[] cache = new Integer[256] 中取出对应的 //Integer对象返回
Integer i1 = 200;// Integer i1 =new Integer(200)
Integer i2 = 200;// Integer i2 =new Integer(200)
System.out.println(i1 == i2);//false,因为new会在堆内存中创建引用地址,i1和i2的引用地址不同
System.out.println(i1.equals(i2));//true,因为Integer类中的equals方法重写后比较是内容
Integer i3 = 100;// 100从Integer[] cache = new Integer[256]中取出100对应的Integer对象
Integer i4 = 100;// 100从同一个cache数组中取出100对应的Integer对象
System.out.println(i3 == i4);//true, i3,i4取出的是从相同数组的同一个对象
System.out.println(i3.equals(i4));//true,因为Integer类中的equals方法重写后比较是内容
}
二.Random类
1.常用方法
public Random():构造方法
public int nextInt(int bound):生成指定范围的随机数 [0,bound) 包含0,不包含boud
public static void main(String[] args) {
Random random = new Random();
int x = random.nextInt(100);//0<=生成的随机数<100
System.out.println(x);
}
