Java 中的 Integer.toString(int i) 与 String.valueOf(int i)

发布于 2024-09-11 02:50:05 字数 288 浏览 4 评论 0原文

我想知道为什么方法 String.valueOf(int i) 存在?我正在使用此方法将 int 转换为 String 并且刚刚发现了 Integer.toString(int i) 方法。

查看这些方法的实现后,我发现第一个方法正在调用第二个方法。因此,我对 String.valueOf(int i) 的所有调用都比直接调用 Integer.toString(int i) 多了一次调用

I am wondering why the method String.valueOf(int i) exists ? I am using this method to convert int into String and just discovered the Integer.toString(int i) method.

After looking the implementation of these methods I saw that the first one is calling the second one. As a consequence all my calls to String.valueOf(int i) involve one more call than directly calling Integer.toString(int i)

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(12

画中仙 2024-09-18 02:50:05

在 String 类型中,我们有几种方法 valueOf

static String   valueOf(boolean b) 
static String   valueOf(char c) 
static String   valueOf(char[] data) 
static String   valueOf(char[] data, int offset, int count) 
static String   valueOf(double d) 
static String   valueOf(float f) 
static String   valueOf(int i) 
static String   valueOf(long l) 
static String   valueOf(Object obj) 

正如我们所看到的,这些方法能够解析所有类型的数字,

就像您所呈现的特定方法的每个实现一样:因此,对于整数,我们有

Integer.toString(int i)

double

Double.toString(double d)

等等,

在我看来,这不是什么历史性的事情,但对于开发人员来说,使用 String 类中的方法 valueOf 比使用正确类型中的方法更有用,因为当我们想要更改类型时,它可以减少我们所做的更改我们正在操作。

示例 1:

public String doStuff(int num) {

  // Do something with num...

  return String.valueOf(num);

 }

示例 2:

public String doStuff(int num) {
  
 // Do something with num...
 
 return Integer.toString(num);

 }

正如我们在示例 2 中看到的,我们必须进行两项更改,这与示例 1 相反。

总而言之,使用 String 类中的 valueOf 方法更加灵活,这就是它在那里可用的原因。

In String type we have several method valueOf

static String   valueOf(boolean b) 
static String   valueOf(char c) 
static String   valueOf(char[] data) 
static String   valueOf(char[] data, int offset, int count) 
static String   valueOf(double d) 
static String   valueOf(float f) 
static String   valueOf(int i) 
static String   valueOf(long l) 
static String   valueOf(Object obj) 

As we can see those method are capable to resolve all kind of numbers

every implementation of specific method like you have presented: So for integers we have

Integer.toString(int i)

for double

Double.toString(double d)

and so on

In my opinion this is not some historical thing, but it is more useful for a developer to use the method valueOf from the String class than from the proper type, as it leads to fewer changes for us to make when we want to change the type that we are operating on.

Sample 1:

public String doStuff(int num) {

  // Do something with num...

  return String.valueOf(num);

 }

Sample2:

public String doStuff(int num) {
  
 // Do something with num...
 
 return Integer.toString(num);

 }

As we see in sample 2 we have to do two changes, in contrary to sample one.

In my conclusion, using the valueOf method from String class is more flexible and that's why it is available there.

尽揽少女心 2024-09-18 02:50:05

一个巨大的区别是,如果您在 null 对象中调用 toString(),您将得到一个 NullPointerException,而使用 String.valueOf()您可能不会检查 null。

One huge difference is that if you invoke toString() in a null object you'll get a NullPointerException whereas, using String.valueOf() you may not check for null.

生生不灭 2024-09-18 02:50:05

只是做同一件事的两种不同方式。这可能是一个历史原因(不记得一个是否先于另一个)。

Just two different ways of doing the same thing. It may be a historical reason (can't remember if one came before the other).

苏佲洛 2024-09-18 02:50:05

String 类为所有基元类型和 Object 类型提供 valueOf 方法,因此我假设它们是可以通过一个类访问的便捷方法。

NB 分析结果

平均 intToString = 5368ms,平均 stringValueOf = 5689ms(对于 100,000,000 次操作)

public class StringIntTest {


    public static long intToString () {
        long startTime = System.currentTimeMillis();
        for (int i = 0; i < 100000000; i++) {
            String j = Integer.toString(i);
        }
        long finishTime = System.currentTimeMillis();

        return finishTime - startTime;
    }

    public static long stringValueOf () {

        long startTime = System.currentTimeMillis();
        for (int i = 0; i < 100000000; i++) {
            String j = String.valueOf(i);
        }
        long finishTime = System.currentTimeMillis();

        return finishTime - startTime;
    }

    public static void main(String[] args) {
        long intToStringElapsed = 0;
        long stringValueOfElapsed = 0;
        for (int i = 0; i < 10; i++) {
            intToStringElapsed += intToString();
            stringValueOfElapsed+= stringValueOf();
        }
        System.out.println("Average intToString = "+ (intToStringElapsed /10));
        System.out.println("Average stringValueOf = " +(stringValueOfElapsed / 10));
    }
}

The String class provides valueOf methods for all primitive types and Object type so I assume they are convenience methods that can all be accessed through the one class.

NB Profiling results

Average intToString = 5368ms, Average stringValueOf = 5689ms (for 100,000,000 operations)

public class StringIntTest {


    public static long intToString () {
        long startTime = System.currentTimeMillis();
        for (int i = 0; i < 100000000; i++) {
            String j = Integer.toString(i);
        }
        long finishTime = System.currentTimeMillis();

        return finishTime - startTime;
    }

    public static long stringValueOf () {

        long startTime = System.currentTimeMillis();
        for (int i = 0; i < 100000000; i++) {
            String j = String.valueOf(i);
        }
        long finishTime = System.currentTimeMillis();

        return finishTime - startTime;
    }

    public static void main(String[] args) {
        long intToStringElapsed = 0;
        long stringValueOfElapsed = 0;
        for (int i = 0; i < 10; i++) {
            intToStringElapsed += intToString();
            stringValueOfElapsed+= stringValueOf();
        }
        System.out.println("Average intToString = "+ (intToStringElapsed /10));
        System.out.println("Average stringValueOf = " +(stringValueOfElapsed / 10));
    }
}
暗恋未遂 2024-09-18 02:50:05

来自 Java 来源:

/**
 * Returns the string representation of the {@code int} argument.
 * <p>
 * The representation is exactly the one returned by the
 * {@code Integer.toString} method of one argument.
 *
 * @param   i   an {@code int}.
 * @return  a string representation of the {@code int} argument.
 * @see     java.lang.Integer#toString(int, int)
 */
public static String valueOf(int i) {
    return Integer.toString(i);
}

所以它们给出了完全相同的结果,并且一个实际上调用了另一个。如果您稍后可能更改类型,String.valueOf 会更灵活。

From the Java sources:

/**
 * Returns the string representation of the {@code int} argument.
 * <p>
 * The representation is exactly the one returned by the
 * {@code Integer.toString} method of one argument.
 *
 * @param   i   an {@code int}.
 * @return  a string representation of the {@code int} argument.
 * @see     java.lang.Integer#toString(int, int)
 */
public static String valueOf(int i) {
    return Integer.toString(i);
}

So they give exactly the same result and one in fact calls the other. String.valueOf is more flexible if you might change the type later.

給妳壹絲溫柔 2024-09-18 02:50:05

如果您查看 String 类的源代码,当您调用 valueOf() 时,它实际上会调用 Integer.toString()

话虽这么说,如果方法调用在编译时没有进行优化(它们可能是这样),Integer.toString() 可能会快一点。

If you look at the source code for the String class, it actually calls Integer.toString() when you call valueOf().

That being said, Integer.toString() might be a tad faster if the method calls aren't optimized at compile time (which they probably are).

花辞树 2024-09-18 02:50:05

String.valueOf() 是满足 API 中指定的约定的最简单方法:“该表示形式正是 整数。一个参数的 toString() 方法。”

The implementation of String.valueOf() that you see is the simplest way to meet the contract specified in the API: "The representation is exactly the one returned by the Integer.toString() method of one argument."

情泪▽动烟 2024-09-18 02:50:05

要回答OP问题,它只是一个帮助包装器来进行其他调用,并且归结为样式选择,仅此而已。我认为这里存在很多错误信息,Java 开发人员能做的最好的事情就是查看每个方法的实现,在任何 IDE 中单击一两次即可完成。您将清楚地看到 String.valueOf(int) 只是为您调用 Integer.toString(int)

因此,差异绝对为零,因为它们都创建一个 char 缓冲区,遍历数字中的数字,然后将其复制到一个新的 String 中并返回它(因此每个都创建一个 String 对象)。唯一的区别是一个额外的调用,编译器无论如何都会将其消除为单个调用。

因此,除了代码一致性之外,调用哪个并不重要。至于关于 null 的注释,它需要一个原语,因此它不能为 null!如果不初始化传递的 int,您将收到编译时错误。因此,它处理空值的方式没有区别,因为在这种情况下它们不存在。

To answer the OPs question, it's simply a helper wrapper to have the other call, and comes down to style choice and that is it. I think there's a lot of misinformation here and the best thing a Java developer can do is look at the implementation for each method, it's one or two clicks away in any IDE. You will clearly see that String.valueOf(int) is simply calling Integer.toString(int) for you.

Therefore, there is absolutely zero difference, in that they both create a char buffer, walk through the digits in the number, then copy that into a new String and return it (therefore each are creating one String object). Only difference is one extra call, which the compiler eliminates to a single call anyway.

So it matters not which you call, other than maybe code-consistency. As to the comments about nulls, it takes a primitive, therefore it can not be null! You will get a compile-time error if you don't initialize the int being passed. So there is no difference in how it handles nulls as they're non-existent in this case.

樱娆 2024-09-18 02:50:05

您不必担心这个额外的调用会导致效率问题。如果有任何成本,那也是最小的,并且从大局来看应该可以忽略不计。

也许两者存在的原因都是为了提供可读性。在许多类型被转换为 String 的情况下,对 String.valueOf(SomeType) 的各种调用可能比各种 SomeType.toString 更具可读性> 来电。

You shouldn't worry about this extra call costing you efficiency problems. If there's any cost, it'll be minimal, and should be negligible in the bigger picture of things.

Perhaps the reason why both exist is to offer readability. In the context of many types being converted to String, then various calls to String.valueOf(SomeType) may be more readable than various SomeType.toString calls.

梦纸 2024-09-18 02:50:05

我的开放是 valueof() 总是调用 tostring() 来表示,因此对于原始类型 valueof 的表示是通用的。java 默认情况下不支持数据类型,但它定义了它与对象和类的工作,它在 cllas 中制作了所有东西并制作object .here Integer.toString(int i) 创建一个仅转换为整数的限制。

my openion is valueof() always called tostring() for representaion and so for rpresentaion of primtive type valueof is generalized.and java by default does not support Data type but it define its work with objaect and class its made all thing in cllas and made object .here Integer.toString(int i) create a limit that conversion for only integer.

野の 2024-09-18 02:50:05

Integer.toString(5) 和 String.valueOf(5) 之间没有区别;

因为 String.valueOf 返回:

public static String valueOf(int i) {
    return Integer.toString(i);
}
public static String valueOf(float f) {
    return Float.toString(f);
}

等等..

There have no differences between Integer.toString(5) and String.valueOf(5);

because String.valueOf returns:

public static String valueOf(int i) {
    return Integer.toString(i);
}
public static String valueOf(float f) {
    return Float.toString(f);
}

etc..

っ〆星空下的拥抱 2024-09-18 02:50:05

使用 String.valueOf() 方法,您不必担心数据(无论是 int、long、char、char[]、boolean、Object),您只需调用:

  • static String valueOf()

使用唯一的语法 String.valueOf() 可以将您作为参数传递的任何内容转换为 String 并返回。

否则,如果您使用 Integer.toString()、Float.toString() 等(即 SomeType.toString()),那么您将必须检查要转换为字符串的参数的数据类型。
因此,最好使用 String.valueOf() 进行此类转换。

如果您有一个包含不同值(如 Integer、Char、Float 等)的对象类数组,那么通过使用 String.valueOf() 方法,您可以轻松地将此类数组的元素转换为 String 形式。相反,如果您想使用 SomeType.toString() 那么首先您需要了解它们的数据类型类(也许通过使用“instanceOf”运算符),然后只有您可以继续进行类型转换。

String.valueOf() 方法在调用时与传递的参数匹配(无论是 Integer、Char、Float 等),并通过使用方法重载调用其参数匹配的“valueOf()”方法,然后在该方法内它们是直接调用相应的“toString()”方法。

因此,我们可以看到如何删除检查数据类型然后调用相应的“toString()”方法的开销。我们只需要调用 String.valueOf() 方法,不关心我们想要转换为字符串的内容。

结论: String.valueOf() 方法的重要性只是以多调用一次为代价。

Using the method, String.valueOf() you do not have to worry about the data(whether it is int,long,char,char[],boolean,Object), you can just call :

  • static String valueOf()

using the only syntax String.valueOf() can whatever you pass as a parameter is converted to String and returned..

Otherwise, if you use Integer.toString(),Float.toString() etc.(i.e. SomeType.toString()) then you will have to check the datatype of parameter that you want to convert into string.
So, its better to use String.valueOf() for such convertions.

If you are having an array of object class that contains different values like Integer,Char,Float etc. then by using String.valueOf() method you can convert the elements of such array into String form easily. On contrary, if you want to use SomeType.toString() then at first you will need to know about there their datatype classes(maybe by using "instanceOf" operator) and then only you can proceed for a typecast.

String.valueOf() method when called matches the parameter that is passed(whether its Integer,Char,Float etc.) and by using method overloading calls that "valueOf()" method whose parameter gets matched, and then inside that method their is a direct call to corresponding "toString()" method..

So, we can see how the overhead of checking datatype and then calling corresponding "toString()" method is removed.Only we need is to call String.valueOf() method, not caring about what we want to convert to String.

Conclusion: String.valueOf() method has its importance just at cost of one more call.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文