zoukankan      html  css  js  c++  java
  • 包装类Integer和String互相转换

    一、包装类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;
    }
    

     

  • 相关阅读:
    nmon系统监控
    Spring框架DataSource
    Spring框架的AOP
    jdk -version could not open jvm.cfg 的解决办法
    Spring框架annotation实现IOC介绍
    Junit4 单元测试框架的常用方法介绍
    页面静态化3 --- 使用PHP页面缓存机制来完成页面静态化(下)操作一个案例(新闻管理系统)
    页面静态化2 --- 使用PHP缓存机制来完成页面静态化(上)(ob_flush和flush函数区别用法)
    页面静态化1 --- 概念(Apache内置压力测试工具使用方法)
    memcached学习笔记6--浅谈memcached的机制 以及 memcached细节讨论
  • 原文地址:https://www.cnblogs.com/joshua317/p/15604600.html
Copyright © 2011-2022 走看看