Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

394
Vistas
difference between List<Integer> arr and var arr

The following code works fine.

List<Integer> arr = new ArrayList<Integer>();
System.out.println(arr.getClass().getSimpleName()); // output: ArrayList
arr.add(0);
arr.add(1);
arr = arr.subList(0,1);

But if you change the first line to

var arr = new ArrayList<Integer>();

an error will occur:

java: incompatible types: java.util.List<java.lang.Integer> cannot be converted to java.util.ArrayList<java.lang.Integer>

However, even if arr is defined in the second way, its type is still ArrayList, so what is the difference?

over 4 years ago · Santiago Trujillo
1 Respuestas
Responde la pregunta

0

When you write

var arr = new ArrayList<Integer>();

the compiler infers the type of the arr variable to be ArrayList<Integer>, so it's equivalent to writing:

ArrayList<Integer> arr = new ArrayList<Integer>();

arr.subList(0,1) returns a List<Integer>, which cannot be assigned to an ArrayList<Integer>, since an ArrayList<Integer> is an implementation of List<Integer>, but not all implementations of List<Integer> are ArrayList<Integer>.

On the other hand, when you declare the variable as List<Integer> arr, you can assign to it any implementation of List<Integer>, which includes the value returned by arr.subList(0,1).

It's important to note that subList does not return an ArrayList. For example, subList() method of ArrayList returns an instance of an inner class called ArrayList$SubList. Such List cannot be assigned to a variable whose type is ArrayList.

over 4 years ago · Santiago Trujillo Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda