Conversion from null to int possible?

前端 未结 6 1944
刺人心
刺人心 2020-12-08 02:05

I know that when I read the answer to this I will see that I have overlooked something that was under my eyes. But I have spent the last 30 minutes trying to figure it out m

6条回答
  •  不知归路
    2020-12-08 02:23

    Just in case you don't have Guava in your project, but already using Apache Commons, you might utilize Apache Lang3 with its ObjectUtils class.

    The usage is basically the same as Guava:

    Integer number = null;
    int notNull = ObjectUtils.firstNonNull(number, 0);
    

    Note, that this method in Guava library works faster, than in Apache. Here is a short comparison I just made on my laptop (Core i7-7500U 2.7 GHz), Oracle Java 8, multiple runs, JVM preheated, results are averaged:

    ╔══════════════╦══════╦══════╦════════╦══════╗
    ║ Library/Runs ║ 1000 ║ 1mln ║ 100mln ║ 1bln ║
    ╠══════════════╬══════╬══════╬════════╬══════╣
    ║ Apache       ║    1 ║   30 ║    782 ║ 9981 ║
    ║ Guava        ║    1 ║   22 ║    120 ║  828 ║
    ╚══════════════╩══════╩══════╩════════╩══════╝
    

    Results are in milliseconds. I don't think you often need to run this method for billions of times, but still, it is always good to have performance comparison

提交回复
热议问题