Integer,int,String相互转换

本文详细介绍了Java中int、Integer与String类型之间的相互转换方法。包括int到Integer的装箱操作,Integer到int的拆箱操作,以及String到Integer和int类型的转换。特别强调了在JDK1.5中引入的自动装箱与自动拆箱特性。

Integer,int,String相互转换用法

这里写图片描述

public class Integer04{
    public static void main(String[] args){
        //int--->Integer
        Integer i1=Integer.valueOf(10);//返回一个表示指定的int值的Integer实例
        //通过构造方法,创建一个Integer实例
        Integer m1=new Integer(10);//封装的基本原理
        //可以直接赋值
        Integer i6 = 6;

        //Integer-->int
        int i2=i1.intValue();//拆箱

        //由于UnBoxing的存在,以下代码在JDK1.5的环境下可以编译通过并运行。 
        Integer wrapperi = new Integer(0);  
        int i5 = wrapperi;  

        //String-->Integer
        Integer i3=Integer.valueOf("10");//返回一个表示指定的String值的Integer实例

        //Integer-->String
        String s1=i3.toString();//返回一个指定的字符串

        //String-->int
        int i4=Integer.parseInt("123");//注意一定要是纯数字

        //int-->String
        String s2=10+"";

        //各种数字类型转换成字符串型:

        String s = String.valueOf( value); // 其中 value 为任意一种数字类型。 
    }
}

其中int装箱可以通过Integer i=new Integer(10)来实现,也可以直接调用Integer.valueOf()的方法实现,同样Sring转换成Integer也可以按照此方法实现,拆箱则是调用的intValue()的方法,至于Integer转String则是调用toString的方法;String转换成int则需要Integer的parse()方法,但是一定要注意:字符串必须是纯数字才可以进行他们之间的转换,而int转String则十分简单:int+字符串,就是字符串,这是基础,容易忘记。

AutoBoxing与UnBoxing带来的转变

在JDK1.5之前,我们总是对集合不能存放基本类型而耿耿于怀。

以下代码在JDK1.5中成为了可能,试想下在JDK1.5之前该如何实现这段代码?
Java代码 收藏代码

int x = 1;   
Collection collection = new ArrayList();   
collection.add(x);//AutoBoxing,自动转换成Integer.   
Integer y = new Integer(2);   
collection.add(y + 2); //y + 2为UnBoxing,自动转换成int。之后再次转换为Integer。  

此特性同样适用于Map
Java代码 收藏代码

Map map = new HashMap();  
int x = 1;  
Integer y = new Integer(2);  
int z = 3;  
map.put(x,y + z);//x自动转换成Integer。y+z自动转换成int。之后再次转换为Integer。  
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值