Integer.parseInt in Java and Integer.valueOf, you silly not tell it?

Integer in Java's class, there are Integer.valueOf (String s) and Integer.parseInt (String s) two static methods, they are able to convert a string to an integer, they in the end what difference does it make? Today have to analyze.

Article directory

First, source code analysis CONCLUSIONS III expansion

First, source code analysis

Integer.parseInt (String s) source:

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

Integer.valueOf (String s) source:

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

We can see from the source code:

Integer.parseInt (String s) will return int constant.

Integer.valueOf (String s) will return an object of type Integer.

Integer.valueOf underlayer () and the Integer.parseInt () uses both Integer.parseInt (String s, int radix) This method, which parses the string as a signed decimal integer, and returns a value of type int .

And Integer.valueOf (String s) in turn calls a public static Integer valueOf (int i), as can be seen from the following source int values ​​will be available directly from the cache when a between -128 and 127 existing Integer objects, but not in the numbers in this range, it will create a new object to call new Integer (i).

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

CONCLUSIONS

If desired the original data int type, use the Integer.parseInt () method.

If the class object to be packed, use valueOf () method.

Similarly Integer, Long, Double and Float is the same reason.

Third, expand

About IntegerCache, values ​​are between -127 to 128. Cache is, the value is returned when located in this section we need is the same example, the following specific reference codes:

//true,会用到缓存
System.out.println(Integer.valueOf(3) == Integer.valueOf(3));

//false,不会用到缓存
System.out.println(Integer.valueOf(500) == Integer.valueOf(500));

//true,equals比较的值,返回true
System.out.println(Integer.valueOf(3).equals(Integer.valueOf(3)));

//true,equals比较的值,返回true
System.out.println(Integer.valueOf(500).equals(Integer.valueOf(500)));

在《阿里巴巴Java开发手册》中,也有对包装类对象比较的说明,内容如下:

  1. 【强制】所有的相同类型的包装类对象之间值的比较,全部使用equals方法比较。 说明:对于Integer var = ? 在-128至127范围内的赋值,Integer对象是在IntegerCache.cache产生,会复用已有对象,这个区间内的Integer值可以直接使用==进行判断,但是这个区间之外的所有数据,都会在堆上产生,并不会复用已有对象,这是一个大坑,推荐使用equals方法进行判断。

推荐阅读
1.SpringCloud系列-整合Hystrix的两种方式)
2.SpringCloud系列-利用Feign实现声明式服务调用)
3.手把手带你利用Ribbon实现客户端的负载均》
4.SpringCloud搭建注册中心与服务注册
5.Spring Boot配置过滤器的两种方式!


限时领取免费Java相关资料,涵盖了Java、Redis、MongoDB、MySQL、Zookeeper、Spring Cloud、Dubbo/Kafka、Hadoop、Hbase、Flink等高并发分布式、大数据、机器学习等技术。
关注下方公众号即可免费领取:

 

Guess you like

Origin www.cnblogs.com/haha12/p/11718025.html