在Java中将long转换为String的有效方法

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/31555628/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-11 11:15:00  来源:igfitidea点击:

Efficient way to convert long to String in Java

java

提问by Matthew

I've been using

我一直在用

long a = 123456789;
String b = a+"";

to convert a longvalue (or int) to String, or in this perspective, treat it as String. My question is, is it ok to do this? Are there any negative impact?

long值(或int)转换为String,或者从这个角度来看,将其视为字符串。我的问题是,这样做可以吗?有没有负面影响?

And is there any difference in using String.valueOf()vs Long.toString()?

使用String.valueOf()vs有什么区别Long.toString()吗?

Thanks

谢谢

采纳答案by daz

It is ok to do this as recent JVM will likely reduce it to:

这样做是可以的,因为最近的 JVM 可能会将其减少为:

String b = String.valueOf(a);

As for negatives, it is not good Java coding style as there is ambiguity. If awas null, would b = "null"? or will an NPE be thrown? You know the answer with experience, but this should be obvious to all readers of your code.

至于否定,它不是好的 Java 编码风格,因为存在歧义。如果anull,那么b = "null"吗?还是会抛出 NPE?您凭经验知道答案,但这对于您的代码的所有读者来说应该是显而易见的。

回答by Konstantin Yovkov

First, your code doesn't compile - you have to append an Lafter the literal:

首先,您的代码无法编译 - 您必须L在文字后附加一个:

Long a = 123456789L;

String.valueOf()and Long.toString()methods both have a primitive longas a parameter, but since ais an wrapper (Long), you can just use the Object#toString()method:

String.valueOf()Long.toString()方法都有一个原语long作为参数,但由于a是一个包装器 ( Long),你可以只使用该Object#toString()方法:

String b = a.toString();

If a, however, is a primitive (long), both String.valueOf()and Long.toString()will do the same, so it's a matter of preference which one to use.

a但是,如果是原始类型 ( long),则String.valueOf()Long.toString()都会执行相同的操作,因此使用哪个是首选问题。