包装类
包装类
针对基本数据类型操作很麻烦,提供了对应基本数据类型的这些类
有了这些类就可以创建出相应的对象,就可以快速便捷的操作数据
byte | short | int | long | char | float | double | boolean | void |
---|---|---|---|---|---|---|---|---|
Byte | Short | Integer | Long | Character | Float | Double | Boolean | Void |
所有包装类的父类-----Number类
基本数据类型直接赋值给对应包装类的对象 ------ 自动封箱
包装类对象直接赋值给基本数据类型 ------- 自动拆箱
包装类对象用xxxValue()把包装类,转成基本数据类型
自动封箱,自动拆箱 --------- JDK1.5新特性
Void:
public class VoidDemo { public static void main(String[] args) { } //表示方法没有返回值 public void m(){ } //返回值一定是null public Void n(){ return null; } }
Integer:封箱 ------- 基本数据类型都可以进行封箱
public class VoidDemo { public static void main(String[] args) { //整型变量 int i=1; //创建了Integer变量 //封箱 ----- 基本数据类型构建成相应包装类的对象 Integer in = new Integer(i); System.out.println(in); // 1 //自动封箱 -- 基本数据类型赋值给对应包装类对象 --- jdk1.5新特性 //底层由 Integer.valueOf(i) 实现; //对应包装类调用valueOf方法,把基本类型转成相应的包装类对象 Integer in = i; System.out.println(in); // 1 } }
Integer:自动拆箱
public class VoidDemo { public static void main(String[] args) { //包装类对象 Integer in = new Integer(3); //包装类对象直接赋值给基本类型---自动拆箱 //底层是根据in.intValue();来实现的 //包装类对象调用XXXValue来让包装类对象转成基本数据类型 int i = in; } }
Integer返回的值:
public class VoidDemo { public static void main(String[] args) { //底层由Integer.valueOf(); //底层传入一个整型值在-128~127范围之内返回的是相同数组的值 Integer in1 = -128; Integer in2 = -128; System.out.println(in1 == in2); //true Integer in3 = 129; Integer in4 = 129; System.out.println(in3 == in4); //false } }
基本类型与包装类进行运算
public class VoidDemo { public static void main(String[] args) { Integer in = 1; int a = 1; //当包装类和基本类型进行计算时,包装类对象会自动拆箱,和基本类型进行运算 System.out.println(in+a); } }
Integer中写入字符串
public class VoidDemo { public static void main(String[] args) { // java.lang.NumberFormatException --- 数据格式异常 // 首先检测第一个字符是否是+或-,后面所有的字符都会检测是否是数字 Integer in1 = new Integer("+12C3"); // 运行报错 Integer in2 = new Integer("123"); // 123 System.out.println(in1); System.out.println(in2); } }
Boolean
public class VoidDemo { public static void main(String[] args) { //字符串中是true,结果是true,忽略大小写 //其他未false Boolean b = new Boolean("true"); System.out.println(b); } }
将字符串转成整型值
public class VoidDemo { public static void main(String[] args) { //将字符串转成整型值 System.out.println(Integer.parseInt("123")); } }
所有包装类对象的哈希码值都是固定的
public class VoidDemo { public static void main(String[] args) { //给什么值就返回多少 System.out.println(Integer.hashCode(10)); //10 System.out.println(Byte.hashCode((byte)10)); //10 System.out.println(Short.hashCode((short)10)); //10 System.out.println(Character.hashCode('1')); //49 System.out.println(Long.hashCode(10L)); //10 System.out.println(Double.hashCode(10.0D)); //1076101120 //为false时是1237 System.out.println(Boolean.hashCode(true)); //1231 } }
保存redis相关笔记