Diferencia entre parseInt y valueOf en java?


¿Cuál es la diferencia entre estos dos métodos? Parecen hacer exactamente lo mismo para mí (también va para parseFloat(), parseDouble(), parseLong() etc, ¿en qué se diferencian de Long.valueOf(string) ?

Editar: También, ¿cuál de estos es preferible y se usa más a menudo por convención?

Author: Click Upvote, 2009-02-03

11 answers

Bueno, la API para Integer.valueOf(String) de hecho, dice que el String se interpreta exactamente como si se le dio a Integer.parseInt(String). Sin embargo, valueOf(String) devuelve un new Integer() object whereas parseInt(String) devuelve un int primitivo.

Si desea disfrutar de los beneficios potenciales de almacenamiento en caché de Integer.valueOf(int), también puedes usar esta monstruosidad:

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

Ahora, si lo que quieres es el objeto y no el primitivo, entonces usar valueOf(String) puede ser más atractivo que hacer un nuevo objeto fuera de parseInt(String) porque el primero está consistentemente presente a través de Integer, Long, Double, etc.

 345
Author: Zach Scrivena,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2009-02-03 23:50:26

De este foro:

parseInt() devuelve primitivo entero tipo (int), donde valueOf regresos java.lang.Integer, que es el objeto representante del entero. Alli son circunstancias donde usted podría querer un objeto entero, en lugar de tipo primitivo.

Por supuesto, otra diferencia obvia es que intValue es un método de instancia por lo que parseInt es una estática método.

 67
Author: Michael Haren,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2009-02-03 20:06:40
Integer.valueOf(s)

Es similar a

new Integer(Integer.parseInt(s))

La diferencia es valueOf() devuelve un Integer, y parseInt() devuelve un int (un tipo primitivo). También tenga en cuenta que valueOf() puede devolver una instancia en caché Integer, lo que puede causar resultados confusos donde el resultado de las pruebas == parece correcto de forma intermitente. Antes de autoboxing podría haber una diferencia en la conveniencia, después de java 1.5 realmente no importa.

Además, Integer.parseInt(s) también puede tomar el tipo de datos primitivo.

 34
Author: Joao da Silva,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2015-05-01 10:11:52

Mira las fuentes Java: valueOf está usando 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 devuelve 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);
}
 14
Author: Paul Verest,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2014-10-28 08:53:29

Entero.parseInt solo puede devolver int como tipo nativo.

Entero.valueOf puede necesitar asignar un objeto Entero, a menos que ese entero sea uno de los preasignados. Esto cuesta más.

Si solo necesita un tipo nativo, use parseInt. Si necesita un objeto, utilice valueOf.

También, debido a esta asignación potencial, autoboxing no es realmente bueno en todos los sentidos. Puede ralentizar las cosas.

 5
Author: iny,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2009-02-03 20:28:28

Porque podría estar usando jdk1.5+ y allí está la conversión automática a int. Así que en su código su primer Entero de retorno y luego auto convertido a int.

Su código es el mismo que

int abc = new Integer(123);
 2
Author: MAR,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2015-07-18 10:44:17

El parse* variations devuelve tipos primitivos y el valueOf versions devuelve Objetos. Creo que las versiones valueOf también usarán un grupo de referencia interno para devolver el MISMO objeto para un valor dado, no solo otra instancia con el mismo valor interno.

 1
Author: basszero,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2009-02-03 20:02:37

Dado que valueOf devuelve un nuevo objeto Entero, ¿por qué el código de abajo es correcto?

String base5String = "230";
int result = Integer.valueOf(base5String);
 0
Author: curious,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2010-12-13 23:51:44

Si comprueba la clase Integer, encontrará ese método valueof call parseInt. La gran diferencia es el almacenamiento en caché cuando llamas a valueof API . Cache si el valor está entre -128 a 127 Por favor encuentre debajo el enlace para más información

Http://docs.oracle.com/javase/7/docs/api/java/lang/Integer.html

 0
Author: Anuj Kumar Jha,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2014-07-23 17:58:28

Valor entero estático público de (Cadena s)

  1. El argumento se interpreta como una representación de un entero decimal con signo, exactamente como si el argumento se le diera al parseInt(java.lang.String).
  2. El resultado es un objeto Entero que representa el valor entero especificado por la cadena.

  3. En otras palabras, este método devuelve un objeto Entero igual al valor de: nuevo entero (Integer.parseInt (s))

 0
Author: shuaihanhungry,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2015-09-29 03:31:14
  1. En el caso de valueOf -> está creando un objeto Entero. no es un tipo primitivo ni un método estático.
  2. En caso de parseInt.parseFloat - > devuelve el tipo primitivo respectivo. y es un método estático.

Debemos usar cualquiera dependiendo de nuestra necesidad. En caso de valueOf ya que está instanciando un objeto. consumirá más recursos si solo necesitamos el valor de algún texto,entonces deberíamos usar parseInt, parseFloat, etc.

 -2
Author: ,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2009-08-26 07:08:04