[java] Java에서 parseInt ()와 valueOf ()가 다른가요?

parseInt()와는 어떻게 다른 valueOf()가요?

그들은 나에게 정확히 같은 일을 할 것으로 보인다 (도 간다 parseFloat(), parseDouble(), parseLong()등, 그들은 어떻게 다르다 Long.valueOf(string)?

또한, 이들 중 어느 것이 바람직하고 관례 적으로 더 자주 사용됩니까?



답변

에 대한 API Integer.valueOf(String)는 실제로 String에 주어진 것처럼 정확하게 해석 된다고 말합니다 Integer.parseInt(String). 그러나 valueOf(String)반환 반면 객체 반환 원시적를 .new Integer()parseInt(String)int

의 캐싱 이점을 즐기고 싶다면 다음과 Integer.valueOf(int)같은 눈 가리기를 사용할 수도 있습니다.

Integer k = Integer.valueOf(Integer.parseInt("123"))

이제, 당신이 원하는 것은 객체가 아닌 경우 원시, 다음 사용 valueOf(String)에서 새로운 객체를 만드는 것보다 더 매력적 수 있습니다 parseInt(String)전자가 일관되게 존재하기 때문에 Integer, Long, Double, 등


답변

에서 이 포럼 :

parseInt()기본 정수 유형 ( int )을 valueOf리턴 하여 정수를 나타내는 객체 인 java.lang.Integer를 리턴합니다
. 기본 유형 대신 Integer 객체를 원하는 경우가 있습니다.

물론 또 다른 명백한 차이점은 intValueparseInt 가 정적 메서드 인 인스턴스 메서드 라는 것입니다.


답변

Integer.valueOf(s)

비슷하다

new Integer(Integer.parseInt(s))

차이점은 valueOf()다시 표시 Integer하고, parseInt()다시 표시 int(원시 형). 또한 valueOf()캐시 된 Integer인스턴스를 반환 할 수 있으므로 ==테스트 결과가 간헐적으로 정확 해 보이는 경우 혼동되는 결과가 발생할 수 있습니다 . 오토 박싱 전에 편의성에 차이가있을 수 있지만, Java 1.5 이후에는 문제가되지 않습니다.

또한 Integer.parseInt(s)기본 데이터 유형도 사용할 수 있습니다.


답변

자바 소스 봐 : valueOf사용이다 parseInt:

/**
 * Parses the specified string as a signed decimal integer value.
 *
 * @param string
 *            the string representation of an integer value.
 * @return an {@code Integer} instance containing the integer value
 *         represented by {@code string}.
 * @throws NumberFormatException
 *             if {@code string} cannot be parsed as an integer value.
 * @see #parseInt(String)
 */
public static Integer valueOf(String string) throws NumberFormatException {
    return valueOf(parseInt(string));
}

parseInt 보고 int

/**
 * Parses the specified string as a signed decimal integer value. The ASCII
 * character \u002d ('-') is recognized as the minus sign.
 *
 * @param string
 *            the string representation of an integer value.
 * @return the primitive integer value represented by {@code string}.
 * @throws NumberFormatException
 *             if {@code string} cannot be parsed as an integer value.
 */
public static int parseInt(String string) throws NumberFormatException {
    return parseInt(string, 10);
}


답변

Integer.parseInt는 int를 기본 유형으로 반환 할 수 있습니다.

정수가 사전 할당 된 것 중 하나가 아닌 한 Integer.valueOf는 실제로 Integer 객체를 할당해야 할 수도 있습니다. 이것은 더 많은 비용이 듭니다.

기본 유형 만 필요한 경우 parseInt를 사용하십시오. 객체가 필요한 경우 valueOf를 사용하십시오.

또한 이러한 잠재적 할당으로 인해 오토 박싱이 실제로 모든면에서 좋은 것은 아닙니다. 속도가 느려질 수 있습니다.


답변

구문 분석 * 변형은 기본 유형을 반환하고 valueOf 버전은 Object를 반환합니다. valueOf 버전은 내부 참조 풀을 사용하여 동일한 내부 값을 가진 다른 인스턴스뿐만 아니라 주어진 값에 대해 SAME 객체를 반환한다고 생각합니다.


답변

jdk1.5 이상을 사용 중일 수 있으므로 int로 자동 변환됩니다. 따라서 코드에서 첫 번째 정수를 반환 한 다음 int로 자동 변환됩니다.

귀하의 코드는

int abc = new Integer(123);