Convertir Long en Entero


¿Cómo convertir un Long valor en un Integer valor en Java?

 245
Author: Cristian Ciupitu, 2011-04-27

12 answers

Integer i = theLong != null ? theLong.intValue() : null;

O si no necesitas preocuparte por null:

// auto-unboxing does not go from Long to int directly, so
Integer i = (int) (long) theLong;

Y en ambas situaciones, puede encontrarse con desbordamientos (porque un Largo puede almacenar un rango más amplio que un entero).

 398
Author: Thilo,
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
2011-04-27 12:26:01

Aquí hay tres maneras de hacerlo:

Long l = 123L;
Integer correctButComplicated = Integer.valueOf(l.intValue());
Integer withBoxing = l.intValue();
Integer terrible = (int) (long) l;

Las tres versiones generan un código de bytes casi idéntico:

 0  ldc2_w <Long 123> [17]
 3  invokestatic java.lang.Long.valueOf(long) : java.lang.Long [19]
 6  astore_1 [l]
 // first
 7  aload_1 [l]
 8  invokevirtual java.lang.Long.intValue() : int [25]
11  invokestatic java.lang.Integer.valueOf(int) : java.lang.Integer [29]
14  astore_2 [correctButComplicated]
// second
15  aload_1 [l]
16  invokevirtual java.lang.Long.intValue() : int [25]
19  invokestatic java.lang.Integer.valueOf(int) : java.lang.Integer [29]
22  astore_3 [withBoxing]
// third
23  aload_1 [l]
// here's the difference:
24  invokevirtual java.lang.Long.longValue() : long [34]
27  l2i
28  invokestatic java.lang.Integer.valueOf(int) : java.lang.Integer [29]
31  astore 4 [terrible]
 112
Author: Sean Patrick Floyd,
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
2013-11-15 10:33:32
Integer intValue = myLong.intValue();
 42
Author: birdy,
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
2012-05-16 09:57:43

Si desea verificar los desbordamientos y tiene Guayaba a mano, hay Ints.checkedCast():

int theInt = Ints.checkedCast(theLong);

La implementación es muy simple, y lanza IllegalArgumentException al desbordamiento:

public static int checkedCast(long value) {
  int result = (int) value;
  checkArgument(result == value, "Out of range: %s", value);
  return result;
}
 18
Author: Jacob Marble,
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
2018-01-16 05:18:58

Tendrás que escribir cast it.

long i = 100L;
int k = (int) i;

Tenga en cuenta que un largo tiene un rango más grande que un int por lo que podría perder datos.

Si estás hablando de los tipos en caja, entonces lee la documentación .

 5
Author: Jeff Foster,
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
2011-04-27 12:27:06

Si está utilizando Java 8, hágalo de la siguiente manera

    import static java.lang.Math.toIntExact;

    public class DateFormatSampleCode {
        public static void main(String[] args) {
            long longValue = 1223321L;
            int longTointValue = toIntExact(longValue);
            System.out.println(longTointValue);

        }
}
 5
Author: Dushyant Sapra,
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
2017-02-17 05:42:05

La mejor manera simple de hacerlo es:

public static int safeLongToInt( long longNumber ) 
    {
        if ( longNumber < Integer.MIN_VALUE || longNumber > Integer.MAX_VALUE ) 
        {
            throw new IllegalArgumentException( longNumber + " cannot be cast to int without changing its value." );
        }
        return (int) longNumber;
    }
 4
Author: Adi,
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-09 13:30:40

Suponiendo que no es nulo longVal

Integer intVal = ((Number)longVal).intValue();

Funciona por ejemplo y se obtiene un Objeto que puede ser un Entero o un Largo. Sé que es feo, pero sucede...

 2
Author: Edwin Miguel,
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
2016-08-31 23:16:30

Visitantes largos = 1000;

Int convVisitors = (int)visitors;

 0
Author: Bala,
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
2017-08-30 06:01:44

En Java 8 se puede utilizar toIntExact. Si desea manejar null valores, utilice:

Integer intVal = longVal == null ? null : Math.toIntExact(longVal);

Lo bueno de este método es que lanza un ArithmeticException si el argumento (long) se desborda un int.

 0
Author: Jasper de Vries,
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
2018-04-06 15:32:02

Usando toIntExact(valor largo) devuelve el valor del argumento largo, lanzando una excepción si el valor se desborda a un int. solo funcionará a nivel de API 24 o superior.

int id = Math.toIntExact(longId);
 0
Author: Anjal Saneen,
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
2018-05-13 03:13:06

En java, hay una manera rigurosa de convertir un long a int

No solo lnog puede convertir en int,cualquier tipo de clase extiende el Número puede convertir a otro tipo de Número en general,aquí le mostraré cómo convertir un largo a int,otro tipo viceversa.

Long l = 1234567L;
int i = org.springframework.util.NumberUtils.convertNumberToTargetClass(l, Integer.class);
 -3
Author: tsaowe,
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
2013-03-04 01:18:16