包装类的常用方法

自作多情 提交于 2019-11-30 04:59:24

包装类的概述:八种类型

byte-Byte;      boolean-Boolean;    short- Short;        char-Character; 

int-Integer;     long-Long;               float-Float;           double-Double  

包装类的用途主要有两个:

>包装类作为和基本数据类型对应的类存在,方便对象的操作。

>包装类包含每种基本数据类型的相关属性,如最大值、最小值等,以及相关的操作方法。

包装类的用法,以Integer为例:

构造方法:

>  public Integer(int value)
//Constructs a newly allocated Integer object that represents the specified int value.
Parameters:
value - the value to be represented by the Integer object.
> public Integer(String s)
        throws NumberFormatException
Constructs a newly allocated Integer object that represents the int value indicated by the String parameter. The string is converted to an int value in exactly the manner used by the parseInt method for radix 10.
Parameters:
s - the String to be converted to an Integer.
Throws:
NumberFormatException - if the String does not contain a parsable integer.
See Also:
parseInt(java.lang.String, int)

通过构造函数可以进行基本数据类型转换为包装类。

常用方法:

1.利用Integer类中的.parseInt(String s)的方法将字符串转成int类型:

public static int parseInt(String s)
                    throws NumberFormatException
如:

int num = Integer.parseInt("12345");

2.利用Integer类中的.parseInt(String s, int radix)的方法用第二个参数提供的基数(二进制,10进制,16进制等)进行解析s返回

int类型的数据:

public static int parseInt(String s,
                           int radix)
                    throws NumberFormatException

如:

 parseInt("0", 10) returns 0
 parseInt("473", 10) returns 473
 parseInt("+42", 10) returns 42
 parseInt("-0", 10) returns 0
 parseInt("-FF", 16) returns -255
 parseInt("1100110", 2) returns 102
 parseInt("2147483647", 10) returns 2147483647
 parseInt("-2147483648", 10) returns -2147483648
 parseInt("2147483648", 10) throws a NumberFormatException
 parseInt("99", 8) throws a NumberFormatException
 parseInt("Kona", 10) throws a NumberFormatException
 parseInt("Kona", 27) returns 411787
3.使用Integer类中的.valueOf(String s)的方法将字符串转成Integer类型

public static Integer valueOf(String s)
                       throws NumberFormatException
如:

Integer in = Integer.valueOf("3455");

4.使用Integer类中的.valueOf(int i)的方法将int类型转成Integer类型

public static Integer valueOf(int i)

如:Integer in = Integer.valueOf(12);//仅作了解,目前编译器会自动转化

5.使用Integer类中的.valueOf(String s,int radix)的方法用第二个参数提供的基数(二进制,10进制,16进制等)进行解析s 

返回Integer对象

public static Integer valueOf(String s,
                              int radix)
                       throws NumberFormatException
如: Integer a = Integer.("1234",10);//返回结果为1234

       Integer b = Integer.("00001010",2);//返回结果为10





标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!