包装类
一、 简介
- 基本数据类型(8种),不是对象,提供了包装类,将基本数据类型封装成对象来操作
- 基本数据类型能和包装类型之间相互转换(除去boolean),和String转换
- 包装类中还包括了基本数据类型相关的属性和其他方法
Number抽象类学习
//获取 int 类型的值
public abstract int intValue();
//获取 long 类型的值
public abstract long longValue();
public abstract float floatValue();
public abstract double doubleValue();
public byte byteValue() {
return (byte)intValue();
}
public short shortValue() {
return (short)intValue();
}
二、基本数据类型和包装类
基本类型 | 默认值 | 包装类型 | 包装类型默认值 |
---|---|---|---|
int | 0 | Integer | null |
long | 0 | Long | null |
boolean | false | Boolean | null |
byte | 0 | Byte | null |
short | 0 | Short | null |
float | 0.0 | Float | null |
double | 0.0 | Double | null |
char | ‘’ | Character | null |
三、常用方法
-
获取最大值 MAX_VALUE,最小值MIN_VALUE
-
转换:
自动拆箱:将包装类转换成基本数据类型
自动封箱:将基本数据类型转为包装类
//自动装箱 Integer integer3 = 10; Integer integer3 = Integer.valueOf(10); //自动拆箱 int intValue = integer3; int intValue = integer3.intValue();
- 将字符串转为包装类,调用**valueOf()**方法
- 将包装类转成基本数据类型(自动拆箱)**xxxValue()**方法
- 将字符串转成基本数据类型,**parseXXX()**方法
- 将包装类转为字符串,toString(),String.valueOf()
-
compare( ) 比较方法:相同为0,前边小为负,前边大为正
-
toBinaryString( ) 二进制转换
-
Integer 有缓存处理 IntegerCache,-128到127之间,在此范围内,使用==判断,会得到true,超过此范围,返回为false,应该使用equals来判断值是否相等
-
Character相关方法
char c='a'; c=Character.toUpperCase(c);//转成大写字母 c=Character.toLowerCase(c);//转成小写字母 boolean lowerCase = Character.isLowerCase(c);//是否是一个小写字母 System.out.println("lowerCase = " + lowerCase); boolean upperCase = Character.isUpperCase(c);//是否是一个大写字母 System.out.println("upperCase = " + upperCase); boolean letter = Character.isLetter(c);//判断是否是字母 System.out.println("letter = " + letter); boolean digit = Character.isDigit(c);//判断是否是数字 System.out.println("digit = " + digit); char c1=' '; boolean spaceChar = Character.isSpaceChar(c1);//判断是否是空格 System.out.println("spaceChar = " + spaceChar); char[] chars={'A','中'}; int i = Character.codePointAt(chars, 1); System.out.println("i = " + i);
拓展内容(面试内容,面试前再回头来听)
-
缓存设计的优点
- 节约空间开销
- 超过缓存范围才重新分配空间
-
Integer 类型和 int 类型不是同一个类型
- 通过方法的重载证明
-
两个方法分别定义 int a = 100000;当int 类型的值,超过 short 的最大值时,存储到常量池里面
public void eat(Integer integer){ int a = 0x186a0; } public void eat(int i){ int a = 0x186a0; }
-
开发过程中建议使用包装类