首页 > 编程语言 >Java中new Long(String s)和Long.valueOf(String s)的区别

Java中new Long(String s)和Long.valueOf(String s)的区别

时间:2022-12-09 14:04:04浏览次数:45  
标签:radix Java String parseLong long code Long NumberFormatException


想要知道new Long(String s)和Long.valueOf(String s)的区别,还是得从源码直接看比较直观

new Long(String s)

Java中new Long(String s)和Long.valueOf(String s)的区别_后端

Long.valueOf(String s)

Java中new Long(String s)和Long.valueOf(String s)的区别_git_02


从源码可以看出,使用new Long(s)和Long.valueOf(s)都会去调用parseLong(s, 10)方法,

parseLong(String s, int radix)

/**
* Parses the string argument as a signed {@code long} 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 {@code long} value is returned.
*
* <p>Note that neither the character {@code L}
* ({@code '\u005Cu004C'}) nor {@code l}
* ({@code '\u005Cu006C'}) is permitted to appear at the end
* of the string as a type indicator, as would be permitted in
* Java programming language source code - except that either
* {@code L} or {@code l} may appear as a digit for a
* radix greater than or equal to 22.
*
* <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 {@code 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 long}.
* </ul>
*
* <p>Examples:
* <blockquote><pre>
* parseLong("0", 10) returns 0L
* parseLong("473", 10) returns 473L
* parseLong("+42", 10) returns 42L
* parseLong("-0", 10) returns 0L
* parseLong("-FF", 16) returns -255L
* parseLong("1100110", 2) returns 102L
* parseLong("99", 8) throws a NumberFormatException
* parseLong("Hazelnut", 10) throws a NumberFormatException
* parseLong("Hazelnut", 36) returns 1356099454469L
* </pre></blockquote>
*
* @param s the {@code String} containing the
* {@code long} representation to be parsed.
* @param radix the radix to be used while parsing {@code s}.
* @return the {@code long} represented by the string argument in
* the specified radix.
* @throws NumberFormatException if the string does not contain a
* parsable {@code long}.
*/
public static long parseLong(String s, int radix)
throws NumberFormatException
{
if (s == null) {
throw new NumberFormatException("null");
}

if (radix < Character.MIN_RADIX) {
throw new NumberFormatException("radix " + radix +
" less than Character.MIN_RADIX");
}
if (radix > Character.MAX_RADIX) {
throw new NumberFormatException("radix " + radix +
" greater than Character.MAX_RADIX");
}

long result = 0;
boolean negative = false;
int i = 0, len = s.length();
long limit = -Long.MAX_VALUE;
long multmin;
int digit;

if (len > 0) {
char firstChar = s.charAt(0);
if (firstChar < '0') { // Possible leading "+" or "-"
if (firstChar == '-') {
negative = true;
limit = Long.MIN_VALUE;
} 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
digit = Character.digit(s.charAt(i++),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;
}

parseLong(String s, int radix)返回long值,这事区别就出来了,对于new Long(String s)是直接将该long值返回,而Long.valueOf(String s)会将返回的long值继续处理Long.valueOf(long l)

Java中new Long(String s)和Long.valueOf(String s)的区别_i++_03


那么从valueOf(long l)方法可以看到再返回结果之前会进行一个判断,判断当值在[-128,127]之间返回的是缓存的值,不在这个值区间了才会通过构造函数返回,从这一点上看会比new Long(String s)更节省空间,提高性能。


标签:radix,Java,String,parseLong,long,code,Long,NumberFormatException
From: https://blog.51cto.com/u_10917175/5925137

相关文章

  • java实现文件对比
    java实现文件对比​​需求​​​​实现效果​​​​后端代码引入​​需求web项目需要实现文件内容对比功能,开发语言是java,也就是通过java实现类似于svn的文件对比功能实现效......
  • Mysql开启ssl加密协议及Java客户端配置操作指南
    Mysql开启ssl加密协议及Java客户端配置操作指南​​Mysql配置​​​​验证Mysql开启SSL​​​​Java客户端操作​​​​生成证书密码​​​​配置数据库连接​​​​工具配......
  • Java格式化日期 微秒
    Java格式化日期微秒​​Date、LocalDateTime格式化微秒值​​​​Date、LocalDateTime互转​​本文主要讲述Java日期格式化及格式化日期到微秒Date、LocalDateTime格式化......
  • Java项目开发小tips
    1、idea对于JS代码的兼容性较差,编写了js代码但是有时候不能正常加载。解决方法:(1)idea缓存清理;  (2)clear-install;先clear,清理完成之后再install。  (3)rebuild重......
  • 小新学Java15-【字节流、字符流】
    一、IO概述1.1什么是IO1.2IO的分类1.3IO的流向说明图解1.4顶级父类们二、字节流2.1一切皆为字节一切文件数据(文本、图片、视频等)在存储时,都是以二进制数字的形......
  • java排序算法
    1.冒泡排序法冒泡排序,轮询两个相邻的数据进行比较,如果条件成立,则数据相互转换。直到数据转换完毕。Integer[]strr={7,5,4,8,6,9,2,3,1,0};for(inti=0;i<strr.l......
  • 关于java程序OOM的优化
    在很多时候,我们使用循环,在循环体中处理逻辑使用的了大量内存,最终导致程序OOM。对此,经过一些测试,最终找出优化方案。策略将不使用的对象赋值为null主动调用GC测试......
  • javascript-代码随想录训练营day24
    77.组合题目链接:https://leetcode.cn/problems/combinations/题目描述:给定两个整数n和k,返回范围[1,n]中所有可能的k个数的组合。你可以按任何顺序返回答案......
  • java-net-php-python-jsp汽车租赁管理系统计算机毕业设计程序
    OverridetheentrypointofanimageIntroducedinGitLabandGitLabRunner9.4.Readmoreaboutthe extendedconfigurationoptions.Beforeexplainingtheav......
  • 从零开始学Java系列之如何使用记事本编写java程序
    前言在上一篇文章中,壹哥给大家介绍了Java中的标识符及其命名规则、规范,Java里的关键字和保留字,以及Java中的编码规范。我们在之前编写案例时,使用的开发工具都是windows自......