17.1.3 Wrapper类的常用函数

本节将以Integer类为例讲述Wrapper类的使用。一个类要处理数据,就要关心这个类中的方法函数。表17.1展示的是这个类的常用方法。

17.1.3 Wrapper类的常用函数 - 图1

【实例17.2】说了那么多理论知识,下面举一个有关的实例,来学习如何使用这些方法函数。


01 ///创建一个包装类的对象x1

02 ///通过x1中的不同方法输出不同的数据类型的数据

03 public class file2

04 {

05 public static void main(String[]args)

06 {

07 int a=20;

08 byte b='a';

09 short c=11;

10 long d=112;

11 float e=11.2f;

12 double f=11.3;

13 Integer x1=new Integer(a);

14 Byte x2=new Byte(b);

15 Short x3=new Short(c);

16 Long x4=new Long(d);

17 Float x5=new Float(e);

18 Double x6=new Double(f);

19 System.out.println(x1);

20 System.out.println(x2);

21 System.out.println(x3);

22 System.out.println(x4);

23 System.out.println(x5);

24 System.out.println(x6);

25 System.out.println(x1.toBinaryString(a));

26 System.out.println(x1.toHexString(a));

27 }

28 }


【代码说明】第7~12行创建了6个基本类型的变量,第13~18行通过构造器创建了6个对象类型的构造对象。第25~26行使用了Wrapper类的两个方法实现类型转换。

【运行效果】


20 97

11 112

11.2

11.3

10100 14


【实例17.3】上面的程序是否看起来有点简单?那么再看看下面这个程序段。


01 ///创建一个包装类的对象i

02 ///自定义一个方法isNumberic

03 public class file3

04 {

05 public static boolean isNumberic(String str)

06 {

07 try

08 {

09 Integer i=new Integer(str);

10 }

11 catch(NumberFormatException e)

12 {

13 return false;

14 }

15 return true;

16 }

17 public static void main(String[]args)

18 {

19 System.out.println(isNumberic("123"));

20 System.out.println(isNumberic("-123.34"));

21 System.out.println(isNumberic("0x12"));

22 System.out.println(isNumberic("453"));

23 System.out.println(isNumberic("1abcd"));

24 System.out.println(isNumberic("-1a33"));

25 26

}

27 }


【代码说明】从上面的程序段可以看出,如果str不是全部由数字组成,就会抛出异常,而异常处理就是返回false。第9行通过Integer类的构造器来构造对象。

【运行效果】


true

false

false

true

false

false


分析上面的例子发现,原来构造器可以作为一个判断的依据。这样,就可以将这个实战经验应用在一些大型的程序中。