您的位置:首页 >Java中Wrapper如何使用
发布于2023-05-02 阅读(0)
扫一扫,手机访问
针对八种基本数据类型定义相应的引用类型—包装类(封装类)。
有了类的特点,就可以调用类中的方法,Java才是真正的面向对象。
八种基本数据类型与其包装类的对应关系:
| 基本数据类型 | 包装类 |
|---|---|
byte | Byte |
short | Short |
int | Integer |
long | Long |
float | Float |
double | Double |
boolean | Boolean |
char | Character |
⭕ 通过包装类的构造器实现:
int i = 500; Integer t = new Integer(i);
⭕ 通过字符串参数构造包装类对象:
Float f = new Float(“4.56”); //Long l = new Long(“asdf”); 报错:NumberFormatException
⭕ 错误举例:
Integer in3 = new Integer("123abc");
System.out.println(in3.toString());
/*
报错:
Exception in thread "main" java.lang.NumberFormatException: For input string: "123abc"
*/⭕ 调用包装类的xxxValue()方法:
boolean b = bObj.booleanValue();
注意:JDK1.5之后,支持自动装箱,自动拆箱。但类型必须匹配
⭕ 通过包装类的构造器实现:
int i = new Integer(“12”);
⭕ 通过包装类的parseXxx(String s)静态方法:
Float f = Float.parseFloat(“12.1”);
⭕ 错误举例:
int num1 = (int)str1; Integer in1 = (Integer)str1; //可能会报NumberFormatException
⭕ 调用字符串重载的valueOf()方法:
String fstr = String.valueOf(2.34f);
⭕ 更直接的方式:
String intStr = 5 + "";

//(1) Object o1 = true ? new Integer(1) : new Double(2.0); System.out.println(o1);//1.0 Object o2; if (true) o2 = new Integer(1); else o2 = new Double(2.0); System.out.println(o2);//1 } //(2) //java Integer i = new Integer(1); Integer j = new Integer(1); System.out.println(i == j);//false Integer m = 1; Integer n = 1; System.out.println(m == n);//true Integer x = 128; Integer y = 128; System.out.println(x == y);//false
售后无忧
立即购买>office旗舰店
售后无忧
立即购买>office旗舰店
售后无忧
立即购买>office旗舰店
售后无忧
立即购买>office旗舰店
正版软件
正版软件
正版软件
正版软件
正版软件
1
2
3
7
9