包装类
概述
在开发中,经常使用包装类对字符串和基本类型数据进行相互转换。- 想想为什么不用强制(隐式)类型转换
就是8个基本数据类型所对应的引用数据类型;
在玩包装类时候,有两点比较重要的东西
创建包装类的对象方式、自动装箱和拆箱的特性;
利用包装类提供的方法对字符串和基本类型数据进行相互转换
作用
因为包装类中提供了一些方法和属性,供程序员可以调用这些方法和属性直接操作数据;
对应关系
规律:
- Int类型的包装类是Integer
- char 类型的包装类是Character
- 其他类型的包装类都是首字母大写

自动拆装箱
学习Example
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18
| Integer a = new Integer(10);
Integer b = Integer.valueOf(10);
Integer c = 10;
int d = c;
ArrayList<Integer> list = new ArrayList<>();
list.add(100);
int e = list.get(0);
|
代码案例
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27
|
public class MyArrayList { public static void main(String[] args) { ArrayList<Integer> list = new ArrayList<>();
list.add(222); list.add(333); Integer i = list.get(1); System.out.println(i * 2); System.out.println(list);
Integer key = 222; list.remove(key); System.out.println(list);
list.remove(Integer.valueOf(222)); System.out.println(list); } }
|
字符串和基本数据类型互转
将任意类型转为字符串
将字符串转为任意基本类型
代码案例
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25
| public class MyInteger { public static void main(String[] args) { int a = 123; String b = a + ""; System.out.println(b.length());
String b1 = Integer.toString(a);
int i = Integer.parseInt(b); System.out.println(i);
double j = Double.parseDouble(b); System.out.println(j);
System.out.println(Integer.MAX_VALUE); System.out.println(Integer.MIN_VALUE); } }
|