Programing

Integer.toString (int i) 및 String.valueOf (int i)

lottogame 2020. 5. 23. 08:53
반응형

Integer.toString (int i) 및 String.valueOf (int i)


왜 방법 String.valueOf(int i)이 존재 하는지 궁금 합니다. 나는 변환하려면이 방법을 사용하고 있습니다 intString그냥 발견 Integer.toString(int i)방법.

이 메소드의 구현을 살펴본 후 첫 번째 메소드가 두 번째 메소드를 호출하는 것을 보았습니다. 결과적으로 String.valueOf(int i)직접 전화하는 것보다 하나 이상의 전화 포함하는 모든 전화Integer.toString(int i)


똑같은 일을하는 두 가지 다른 방법. 역사적인 이유 일 수 있습니다 (하나가 다른 것보다 먼저 왔는지 기억할 수 없음).


문자열 타입에는 여러 가지 메소드 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.toString(double d)

등등

제 생각에는 이것은 역사적인 일이 아니지만 개발자가 valueOf변경 사항이 적기 때문에 개발자가 올바른 유형보다 String 클래스 의 메소드를 사용하는 것이 더 유용합니다 .

샘플 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과 달리 두 가지 변경을 수행해야합니다.

결론적 valueOf으로 String 클래스 메소드를 사용하는 것이 더 유연하므로 거기에서 사용할 수 있습니다.


한 가지 큰 차이점은 호출하는 경우이다 toString()널 객체 당신이 얻을 것이다 NullPointerException사용하는 반면, String.valueOf()널 (null)을 확인하지 않을 수 있습니다 당신을.


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

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가 더 유연합니다.


String클래스 의 소스 코드를 보면 실제로 호출 Integer.toString()할 때 호출 valueOf()합니다.

Integer.toString(), 메소드 호출이 컴파일 타임에 최적화되지 않으면 아마도 더 빠를 수 있습니다.


이 구현은 String.valueOf()API에 지정된 계약을 충족하는 가장 간단한 방법입니다. "표현은 정확히 Integer.toString()하나의 인수 메소드에 의해 리턴 된 것 입니다."


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.


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.


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..


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.


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.


toString()

  1. is present in Object class, generally overrided in derived class
  2. typecast to appropriate class is necessary to call toString() method.

valueOf()

  1. Overloaded static method present in String class.
  2. handles primitive types as well as object types.

    Integer a = null;
    System.out.println(Integer.toString()) ; NUll pointer exception
    System.out.println(String.valueOf() ; give NULL as value
    

check this link its very good. http://code4reference.com/2013/06/which-one-is-better-valueof-or-tostring/

참고URL : https://stackoverflow.com/questions/3335737/integer-tostringint-i-vs-string-valueofint-i

반응형