前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >包装类Integer和String互相转换

包装类Integer和String互相转换

作者头像
joshua317
发布2021-11-30 16:59:14
2810
发布2021-11-30 16:59:14
举报
文章被收录于专栏:技术博文技术博文

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

代码语言:javascript
复制
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)方法

代码语言:javascript
复制
/**
 * 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)方法

代码语言:javascript
复制
/**
 * 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;
}
本文参与 腾讯云自媒体分享计划,分享自作者个人站点/博客。
原始发表:2021-11-25 ,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 作者个人站点/博客 前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体分享计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
目录
  • 一、包装类Integer和String互相转换
  • 二、拓展Integer.parseInt(String str)方法的原理
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档