Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 435
Acuzio Avatar asked Jun 14 '26 00:06

Acuzio


1 Answers

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.

like image 134
Eran Avatar answered Jun 16 '26 13:06

Eran