最新国产好看的视频,伊人天堂AV在线,国产Aaaaaa视频,蜜臀视频在线观看一区,人妻av色图,密臀久久久精品影片,青青视频免费观看毛片,久草在线观看视,国产三级精品色情在线

解讀Integer類的parseInt和valueOf的區(qū)別

 更新時間:2022年11月22日 10:26:05   作者:bai_student  
這篇文章主要介紹了解讀Integer類的parseInt和valueOf的區(qū)別,具有很好的參考價值,希望對大家有所幫助。如有錯誤或未考慮完全的地方,望不吝賜教

Integer類的parseInt和valueOf區(qū)別

我們平時應(yīng)該都用過或者見過parseInt和valueOf這兩個方法。一般我們是想把String類型的字符數(shù)字轉(zhuǎn)成int類型。從這個功能層面來說,這兩個方法都一樣,都可以勝任這個功能。

但是,我們進入源碼,看下Integer類下這兩個方法

我們看parseInt()這個方法是如何實現(xiàn)的

public static int parseInt(String s) throws NumberFormatException {
? ? return parseInt(s,10);
}

我們再看valueOf()是如何實現(xiàn)的

public static Integer valueOf(String s) throws NumberFormatException {
? ? return Integer.valueOf(parseInt(s, 10));
}

從代碼,我們起碼看到了兩點:返回結(jié)果類型不一樣,parseInt方法返回的是int基本類型,valueOf方法返回的是Integer的包裝類型

valueOf方法實際上是調(diào)用了parseInt方法,也就是說,如果我們僅僅只需要得到字符串類型字符數(shù)值對應(yīng)的整數(shù)數(shù)值,那我們大可不必調(diào)用valueOf,因為這樣得到整形數(shù)值之后還要做一個裝箱的操作,將int封裝為Integer。

寫代碼測試效率:

public class StringDemo {
? ? public static void main(String[] args) {
? ? ? ? // TODO Auto-generated method stub
? ? ? ? String str = "123";
? ? ? ? long startTime = System.currentTimeMillis();
? ? ? ? for(int i = 0;i<100000000;i++){
? ? ? ? ? ? Integer.parseInt(str);
? ? ? ? }
? ? ? ? long endTime = System.currentTimeMillis();
? ? ? ? System.out.println(endTime-startTime);
? ? }
}

如下代碼:

public class StringDemo {
? ? public static void main(String[] args) {
? ? ? ? // TODO Auto-generated method stub
? ? ? ? String str = "123";
? ? ? ? long startTime = System.currentTimeMillis();
? ? ? ? for(int i = 0;i<100000000;i++){
? ? ? ? ? ? Integer.valueOf(str);
? ? ? ? }
? ? ? ? long endTime = System.currentTimeMillis();
? ? ? ? System.out.println(endTime-startTime);
? ? }
}

分別測試三遍,得到的時間如下,可以看到paraseInt()的效率更好。

方法第一次時長第二次時長第三次時長
parseInt()294629652952
valueOf()312431173126

Integer的parseInt與value of原理

我一直使用Integer的轉(zhuǎn)換,包括Long,枚舉等,從來沒有注意它是怎么實現(xiàn)的,最近有個業(yè)務(wù)組轉(zhuǎn)換報錯了,想看看是如何實現(xiàn)的。據(jù)筆者猜測:ASCII碼轉(zhuǎn)換?這是常用的計量,什么大寫變小寫都是這樣實現(xiàn)的。下面看看如何實現(xiàn)的吧

1. demo構(gòu)建

public class StringParseInt {
    public static void main(String[] args) {
        String str = "-1234";
        int i = Integer.parseInt(str);
        int y = Integer.valueOf(str);
 
        System.out.println(i + "\t" + y);
    }
}

輸出都正常,關(guān)鍵是看怎么實現(xiàn)的

2. Integer的實現(xiàn)方式

2.1 value of 

    public static Integer valueOf(String s) throws NumberFormatException {
        return Integer.valueOf(parseInt(s, 10));
    }

本質(zhì)還是parseInt,從這點看與parseInt沒有區(qū)別;但是這里有裝箱,如果接收值是int建議直接使用parseInt,省去裝箱的過程。

    public static Integer valueOf(int i) {
        if (i >= IntegerCache.low && i <= IntegerCache.high)
            return IntegerCache.cache[i + (-IntegerCache.low)];
        return new Integer(i);
    }

如果在緩存數(shù)組,直接使用,看看緩存數(shù)組怎么來的

    private static class IntegerCache {
        //下限固定-128
        static final int low = -128;
        //上限沒有初始化
        static final int high;
        //核心緩存數(shù)組
        static final Integer cache[];
        //類加載初始化
        static {
            // high value may be configured by property
            //初始127上限
            int h = 127;
            //VM參數(shù)java.lang.Integer.IntegerCache.high可以配置Integer的最大上限
            String integerCacheHighPropValue =
                sun.misc.VM.getSavedProperty("java.lang.Integer.IntegerCache.high");
            if (integerCacheHighPropValue != null) {
                try {
                    //我沒設(shè)置的值,如果不是int字符串型就會報錯,然后被捕獲
                    int i = parseInt(integerCacheHighPropValue);
                    //取大,對比127;也就是至少是127
                    i = Math.max(i, 127);
                    // Maximum array size is Integer.MAX_VALUE
                    // 上面官方注釋很明顯了,這里減128再減1是因為low是-128
                    h = Math.min(i, Integer.MAX_VALUE - (-low) -1);
                } catch( NumberFormatException nfe) {
                    // If the property cannot be parsed into an int, ignore it.
                }
            }
            high = h;
 
            //創(chuàng)建緩存數(shù)組,如果設(shè)置java.lang.Integer.IntegerCache.high,不宜設(shè)置過大,過大很占連續(xù)空間
            cache = new Integer[(high - low) + 1];
            int j = low;
            //初始化緩存
            for(int k = 0; k < cache.length; k++)
                cache[k] = new Integer(j++);
 
            // range [-128, 127] must be interned (JLS7 5.1.7)
            //斷言至少127,JLS7
            assert IntegerCache.high >= 127;
        }
 
        private IntegerCache() {}
    }

從源碼看Integer內(nèi)部類裝載時,會初始化一個緩存空間,存儲Integer對象。很多面試時就會被這個坑了,初始化的緩存對象地址取值是一致的,可以使用==作對比;然后超過這個范圍的Integer就不能了,要使用Integer的eq方法

    public boolean equals(Object obj) {
        if (obj instanceof Integer) {
            return value == ((Integer)obj).intValue();
        }
        return false;
    }

因為自動裝箱,實際上使用的value of方法,默認情況下,-128~127使用緩存對象。 

2.2 parseInt

    /**
     * 這段注釋尤為重要,定義了符號位,定義了10進制數(shù)字
     * 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 {
        return parseInt(s,10);
    }

重點來哦,String能轉(zhuǎn)為int的本質(zhì),這里需要傳一個核心參數(shù),Integer給我們默認了10進制,其他類型也是相同,比如Long

    public static long parseLong(String s) throws NumberFormatException {
        return parseLong(s, 10);
    }

因為轉(zhuǎn)換后的就是10進制的數(shù)字,可供使用。

進一步分析parseInt(String s, int radix);radix即進制的意思。

    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,至少要2進制
        if (radix < Character.MIN_RADIX) {
            throw new NumberFormatException("radix " + radix +
                                            " less than Character.MIN_RADIX");
        }
        //進制不能大于36
        if (radix > Character.MAX_RADIX) {
            throw new NumberFormatException("radix " + radix +
                                            " greater than Character.MAX_RADIX");
        }
 
        int result = 0;
        //正負標記,默認正
        boolean negative = false;
        //字符串長度
        int i = 0, len = s.length();
        int limit = -Integer.MAX_VALUE;
        int multmin;
        int digit;
        //干活了
        if (len > 0) {
            //首位字符
            char firstChar = s.charAt(0);
            //這里玩了個計謀,0字符的ASCII是48,后面的數(shù)字包括ABCDEF的ASCII都比0大;
            //其中 + 43; - 45
            //只有帶符號位的會判斷,其他就默認正數(shù)
            if (firstChar < '0') { // Possible leading "+" or "-"
                //負數(shù)
                if (firstChar == '-') {
                    negative = true;
                    limit = Integer.MIN_VALUE;
                //非負即正,因為小于'0'
                } else if (firstChar != '+')
                    throw NumberFormatException.forInputString(s);
 
                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
                // 拿到字符,轉(zhuǎn)換為ASCII數(shù)字并按進制轉(zhuǎn)為數(shù)字
                digit = Character.digit(s.charAt(i++),radix);
                //不能帶符號位,前面已經(jīng)驗證了
                if (digit < 0) {
                    throw NumberFormatException.forInputString(s);
                }
                //最小限制,但是這里是一個負數(shù)
                if (result < multmin) {
                    throw NumberFormatException.forInputString(s);
                }
                //由于是從高位向低位,所以需要進制;字符每往后走,需要乘進制
                result *= radix;
                //同樣最小驗證,可能在某些地方有用,暫時沒看出來
                if (result < limit + digit) {
                    throw NumberFormatException.forInputString(s);
                }
                //這里使用反向進位,為了照顧字符從前往后,也可以字符從后往前正向進位
                result -= digit;
            }
        } else {
            throw NumberFormatException.forInputString(s);
        }
        //負數(shù)正數(shù)校正,上面的算法是反向進位
        return negative ? result : -result;
    }

這里說一下Character.digit(s.charAt(i++),radix)

    public static int digit(char ch, int radix) {
        return digit((int)ch, radix);
    }

digit就是數(shù)字的意思,這里直接把char字符強轉(zhuǎn)int類型,即ASCII數(shù)字,然后按照進制轉(zhuǎn)換成相應(yīng)的數(shù)字 

小結(jié):類型轉(zhuǎn)換其實是字符的ASCII的解析符號位,并按字符轉(zhuǎn)為數(shù)字,然后使用逆向負進位方式生成數(shù)字,最后修正符號得出我們想要的結(jié)果。算法符合了字符串解析的順序,不符合人類的思維習(xí)慣。

以上為個人經(jīng)驗,希望能給大家一個參考,也希望大家多多支持腳本之家。

相關(guān)文章

  • 將本地jar包安裝進入maven倉庫(實現(xiàn)方法)

    將本地jar包安裝進入maven倉庫(實現(xiàn)方法)

    下面小編就為大家?guī)硪黄獙⒈镜豭ar包安裝進入maven倉庫(實現(xiàn)方法)。小編覺得挺不錯的,現(xiàn)在就分享給大家,也給大家做個參考。一起跟隨小編過來看看吧
    2017-06-06
  • java中如何實現(xiàn) zip rar 7z 壓縮包解壓

    java中如何實現(xiàn) zip rar 7z 壓縮包解壓

    這篇文章主要介紹了java中如何實現(xiàn) zip rar 7z 壓縮包解壓問題,具有很好的參考價值,希望對大家有所幫助。如有錯誤或未考慮完全的地方,望不吝賜教
    2023-07-07
  • IntelliJ IDEA 熱部署插件JRebel的使用

    IntelliJ IDEA 熱部署插件JRebel的使用

    這篇文章主要介紹了IntelliJ IDEA 熱部署插件JRebel的使用,小編覺得挺不錯的,現(xiàn)在分享給大家,也給大家做個參考。一起跟隨小編過來看看吧
    2018-12-12
  • SpringBoot?自定義注解實現(xiàn)涉密字段脫敏

    SpringBoot?自定義注解實現(xiàn)涉密字段脫敏

    關(guān)于數(shù)據(jù)脫敏,網(wǎng)上的文章都是硬編碼規(guī)則,比如對身份證,手機號,郵件地址等固定寫法脫敏。本文在此基礎(chǔ)上,拓展動態(tài)從數(shù)據(jù)庫查出涉密關(guān)鍵字執(zhí)行脫敏操作。感興趣的同學(xué)可以參考閱讀
    2023-03-03
  • java request.getParameter中文亂碼解決方法

    java request.getParameter中文亂碼解決方法

    今天跟大家分享幾個解決java Web開發(fā)中,request.getParameter()獲取URL中文參數(shù)亂碼的解決辦法,需要的朋友可以參考下
    2020-02-02
  • 關(guān)于@Query注解的用法(Spring Data JPA)

    關(guān)于@Query注解的用法(Spring Data JPA)

    這篇文章主要介紹了關(guān)于@Query注解的用法(Spring Data JPA),具有很好的參考價值,希望對大家有所幫助。如有錯誤或未考慮完全的地方,望不吝賜教
    2022-03-03
  • Flink實現(xiàn)特定統(tǒng)計的歸約聚合reduce操作

    Flink實現(xiàn)特定統(tǒng)計的歸約聚合reduce操作

    這篇文章主要介紹了Flink實現(xiàn)特定統(tǒng)計的歸約聚合reduce操作,文中通過示例代碼介紹的非常詳細,對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價值,需要的朋友們下面隨著小編來一起學(xué)習(xí)吧
    2023-02-02
  • Java 判斷實體對象及所有屬性是否為空的操作

    Java 判斷實體對象及所有屬性是否為空的操作

    這篇文章主要介紹了Java 判斷實體對象及所有屬性是否為空的操作,具有很好的參考價值,希望對大家有所幫助。一起跟隨小編過來看看吧
    2020-12-12
  • 分析ABA問題的本質(zhì)及其解決辦法

    分析ABA問題的本質(zhì)及其解決辦法

    CAS的全稱是compare and swap,它是java同步類的基礎(chǔ),java.util.concurrent中的同步類基本上都是使用CAS來實現(xiàn)其原子性的。本文將介紹ABA問題的本質(zhì)及其解決辦法。
    2021-06-06
  • SpringBoot超詳細分析啟動流程

    SpringBoot超詳細分析啟動流程

    今天小編就為大家分享一篇關(guān)于SpringBoot整個啟動過程的分析,小編覺得內(nèi)容挺不錯的,現(xiàn)在分享給大家,具有很好的參考價值,需要的朋友一起跟隨小編來看看吧
    2022-07-07

最新評論

邮箱| 彭山县| 犍为县| 安丘市| 万源市| 汾阳市| 建宁县| 松溪县| 郸城县| 岳阳县| 咸宁市| 高青县| 宁阳县| 渑池县| 应城市| 宜春市| 蓬莱市| 萨嘎县| 重庆市| 昭平县| 杨浦区| 治多县| 郧西县| 稷山县| 卢龙县| 安康市| 平阴县| 阿拉善左旗| 镇远县| 彭泽县| 新竹市| 长宁县| 九寨沟县| 三门峡市| 临武县| 临汾市| 溆浦县| 灵宝市| 登封市| 东乡族自治县| 滦平县|