Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

390
Views
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 answers
Answer question

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 Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!