This question already has answers here:
How do I convert from int to String?
                                
                                    (19个回答)
                                
                        
                2年前关闭。
            
        

有一段时间,每当我需要一个整数作为字符串时,我就一直在写:

int a = 22;
String b = a + "";


我想知道在参考时是否应该考虑任何差异

String b = String.valueOf(a)
//or
String b = Integer.toString(a)


与“惰性铸造”相比,使用上述方法是否有任何好处?或者在引擎盖下,所有上述方法都相同吗?

最佳答案

String.java中的源代码,String#valueOf调用Integer#toString

/**
 * 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);
}


并且Integer.toString

public static String toString(int i) {
    if (i == Integer.MIN_VALUE)
        return "-2147483648";
    int size = (i < 0) ? stringSize(-i) + 1 : stringSize(i);
    char[] buf = new char[size];
    getChars(i, size, buf);
    return new String(buf, true);
}


因此,我会坚持使用Integer#toString

关于String b = a + "":


这是一种反模式,应避免使用,因为它会创建不必要数量的String对象。

关于java - 这些int到String方法之间有什么区别,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/46678187/

10-11 22:44
查看更多