包装类Integer和String互相转换

本文为joshua317原创文章,转载请注明:转载自joshua317博客 包装类Integer和String互相转换 - joshua317的博客

一、包装类Integer和String互相转换

package com.joshua317;

public class Main {

    public static void main(String[] args) {
        Integer i = 100;
        //包装类Integer ---> String
        //方式一:直接后面跟空字符串
        String str1 = i + "";
        //方式二:调用String类的静态方法valueOf()
        String str2 = String.valueOf(i);
        //方式三:调用Integer类的成员方法toString()
        String str3 = i.toString();
        //方式四:调用Integer类的静态方法toString()
        String str4 = Integer.toString(i);
        System.out.println(str1);
        System.out.println(str2);
        System.out.println(str3);
        System.out.println(str4);

        //String ---> 包装类Integer
        String str5 = "12345";
        //方式一:调用Integer类的静态方法parseInt()
        Integer i2 = Integer.parseInt(str5);
        //方式二:调用Integer类的静态方法valueOf()
        Integer i3 = Integer.valueOf(str5);
        //方式三:调用Integer类的静态方法valueOf()返回一个Integer,然后intValue()拆箱返回int,再自动装箱
        Integer i4 = Integer.valueOf(str5).intValue();
        //方式四:调用Integer类的构造方法
        Integer i5 = new Integer(str5);

        System.out.println(i2);
        System.out.println(i3);
        System.out.println(i4);
        System.out.println(i5);
    }
}

二、拓展Integer.parseInt(String str)方法的原理

Integer.parseInt(String str)方法

/**
 * Parses the string argument as a signed decimal integer. The
 * characters in the string must all be decimal digits, except
 * that the first character may be an ASCII minus sign {@code '-'}
 * ({@code '\u005Cu002D'}) to indicate a negative value or an
 * ASCII plus sign {@code '+'} ({@code '\u005Cu002B'}) to
 * indicate a positive value. The resulting integer value is
 * returned, exactly as if the argument and the radix 10 were
 * given as arguments to the {@link #parseInt(java.lang.String,
 * int)} method.
 *
 * @param s    a {@code String} containing the {@code int}
 *             representation to be parsed
 * @return     the integer value represented by the argument in decimal.
 * @exception  NumberFormatException  if the string does not contain a
 *               parsable integer.
 */
public static int parseInt(String s) throws NumberFormatException {
    //内部默认调用parseInt(String s, int radix),radix默认设置为10,即十进制
    return parseInt(s,10);
}

Integer.parseInt(String s, int radix)方法

/**
 * Parses the string argument as a signed integer in the radix
 * specified by the second argument. The characters in the string
 * must all be digits of the specified radix (as determined by
 * whether {@link java.lang.Character#digit(char, int)} returns a
 * nonnegative value), except that the first character may be an
 * ASCII minus sign {@code '-'} ({@code '\u005Cu002D'}) to
 * indicate a negative value or an ASCII plus sign {@code '+'}
 * ({@code '\u005Cu002B'}) to indicate a positive value. The
 * resulting integer value is returned.
 *
 * <p>An exception of type {@code NumberFormatException} is
 * thrown if any of the following situations occurs:
 * <ul>
 * <li>The first argument is {@code null} or is a string of
 * length zero.
 *
 * <li>The radix is either smaller than
 * {@link java.lang.Character#MIN_RADIX} or
 * larger than {@link java.lang.Character#MAX_RADIX}.
 *
 * <li>Any character of the string is not a digit of the specified
 * radix, except that the first character may be a minus sign
 * {@code '-'} ({@code '\u005Cu002D'}) or plus sign
 * {@code '+'} ({@code '\u005Cu002B'}) provided that the
 * string is longer than length 1.
 *
 * <li>The value represented by the string is not a value of type
 * {@code int}.
 * </ul>
 *
 * <p>Examples:
 * <blockquote><pre>
 * 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
 * </pre></blockquote>
 *
 * @param      s   the {@code String} containing the integer
 *                  representation to be parsed
 * @param      radix   the radix to be used while parsing {@code s}.
 * @return     the integer represented by the string argument in the
 *             specified radix.
 * @exception  NumberFormatException if the {@code String}
 *             does not contain a parsable {@code int}.
 */
public static int parseInt(String s, int radix)
            throws NumberFormatException
{
    /*
     * WARNING: This method may be invoked early during VM initialization
     * before IntegerCache is initialized. Care must be taken to not use
     * the valueOf method.
     */

    //判断字符是否为null
    if (s == null) {
        throw new NumberFormatException("null");
    }

    //进制是否小于最小进制2,Character.MIN_RADIX值为2
    if (radix < Character.MIN_RADIX) {
        throw new NumberFormatException("radix " + radix +
                                        " less than Character.MIN_RADIX");
    }
    //进制是否大于最大进制36,Character.MAX_RADIX值为36
    if (radix > Character.MAX_RADIX) {
        throw new NumberFormatException("radix " + radix +
                                        " greater than Character.MAX_RADIX");
    }

    int result = 0;
    //是否是负数
    boolean negative = false;
    //char字符数组下标和长度
    int i = 0, len = s.length();
    //限制
    int limit = -Integer.MAX_VALUE;
    int multmin;
    int digit;
    //判断字符长度是否大于0,否则抛出异常
    if (len > 0) {
        //第一个字符是否是符号
        char firstChar = s.charAt(0);
        //根据ascii码表看出加号(43)和负号(45)对应的,十进制数小于'0'(48)的
        if (firstChar < '0') { // Possible leading "+" or "-"
            //是负号
            if (firstChar == '-') {
                //负号属性设置为true
                negative = true;
                limit = Integer.MIN_VALUE;
            } else if (firstChar != '+')//不是负号也不是加号则抛出异常
                throw NumberFormatException.forInputString(s);

            //如果有符号(加号或者减号)且字符串长度为1,则抛出异常
            if (len == 1) // Cannot have lone "+" or "-"
                throw NumberFormatException.forInputString(s);
            i++;
        }
        multmin = limit / radix;
        while (i < len) {
            // Accumulating negatively avoids surprises near MAX_VALUE
            //返回指定基数中字符表示的数值。(此处是十进制数值)
            digit = Character.digit(s.charAt(i++),radix);
            //小于0,则为非radix进制数
            if (digit < 0) {
                throw NumberFormatException.forInputString(s);
            }
            //这里是为了保证下面计算不会超出最大值
            if (result < multmin) {
                throw NumberFormatException.forInputString(s);
            }
            result *= radix;
            if (result < limit + digit) {
                throw NumberFormatException.forInputString(s);
            }
            result -= digit;
        }
    } else {
        throw NumberFormatException.forInputString(s);
    }
    //根据上面得到的是否负数,返回相应的值
    return negative ? result : -result;
}

本文为joshua317原创文章,转载请注明:转载自joshua317博客 包装类Integer和String互相转换 - joshua317的博客

### Java 数据型相互转换指南 Java 中的数据转换分为**基本数据型之间的转换****基本型与引用型之间的转换**。转换方式包括**隐式转换**(自动转换**显式转换**(强制转换),同时也支持字符串与数值型之间的转换。 #### 基本数据型之间的转换Java 中,当两个不同型的数值进行运算时,系统会自动进行型提升(隐式转换)。例如,`byte`、`short` `char` 在运算时会自动提升为 `int`,而 `int` 与 `float` 运算时,`int` 会被提升为 `float`,以此推。若需要将较大范围的转换为较小范围的型,则必须使用强制转换: ```java double d = 9.78; int i = (int) d; // 强制转换,结果为9 ``` 隐式转换的优先级顺序为:`byte → short → int → long → float → double`。[^3] #### 基本型与包装之间的转换 Java 提供了基本型的包装(如 `Integer`、`Double` 等),可以通过自动装箱(boxing)拆箱(unboxing)实现基本型与引用型之间的转换: ```java int primitive = 10; Integer wrapper = primitive; // 自动装箱 int backToPrimitive = wrapper; // 自动拆箱 ``` 对于字符串与基本型的转换,可以使用包装的静态方法,如 `Integer.parseInt()` 或 `Double.parseDouble()`: ```java String str = "123"; int num = Integer.parseInt(str); double d = Double.parseDouble(str); ``` 也可以使用 `valueOf()` 方法创建包装对象: ```java Integer obj = Integer.valueOf("123"); // 可能缓存对象 ``` 在性能敏感场景中,推荐使用 `parseXXX()` 方法,因为其直接返回基本型,避免了不必要的对象创建。[^3] #### 引用型之间的转换 引用型之间的转换需要考虑继承关系。如果两个之间存在继承关系,可以使用显式转换。例如: ```java Object obj = new String("Hello"); String str = (String) obj; // 向下转型 ``` 从 Java 16 开始,引入了**模式匹配**(Pattern Matching)来简化型检查转换: ```java if (obj instanceof String s) { System.out.println(s.length()); // 自动转换并使用 } ``` 这种语法避免了冗余的型检查强制转换操作,提高了代码的可读性安全性。[^3] #### 字符串与其他型的转换 除了基本型,Java 还支持将字符串转换为其他数据型,例如日期、集合等。对于日期型,通常使用 `SimpleDateFormat` 进行转换: ```java String dateStr = "2023-01-01"; SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd"); Date date = sdf.parse(dateStr); ``` 对于集合型,可以使用 `Arrays.asList()` 或 `new ArrayList<>()` 构造方式将数组转换为列表: ```java String[] arr = {"a", "b", "c"}; List<String> list = Arrays.asList(arr); ``` #### 转换性能优化 - **基本型自动转换**:耗时 1-2 纳秒,通常无需优化。 - **强制转换**:耗时 2-5 纳秒,应避免在循环内频繁使用。 - **字符串转数值**:耗时 150-200 纳秒,建议缓存重复转换的结果。 - **包装拆箱**:耗时 5-10 纳秒,优先使用基本型数组。 #### 最新特性中的转换Java 14 开始,`switch` 表达式支持自动型匹配: ```java Object obj = 3.14; switch (obj) { case Integer i -> System.out.println("整数"); case Double d -> System.out.println("双精度"); default -> System.out.println("其他"); } ``` Java 16 引入的模式匹配进一步简化了型判断转换流程。 --- ###
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值