Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

392
Visualizações
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 Respostas
Responde à pergunta

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 Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda