Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

The limitation of Arrays.asList() is not true in Thinking in Java 4th Edition [closed]

In this book, it says :

A limitation of Arrays.asList() is that it takes a best guess about the resulting type of the List, and doesn't pay attention to what you are assigning it to.

The book is Thinking in Java By Bruce Eckel

However, the following code is working fine, contrary to code shown in this book page 280

public class Main{

    public static void main(String[] args) {
        List<Snow> snow = Arrays.asList(new Light(), new Heavy());
    }
}
class Snow {}
class Powder extends Snow {}
class Light extends Powder {}
class Heavy extends Powder {}

Java 1.8 , IntelliJ, Windows 7 enter image description here

Any thoughts are appreciated.

like image 312
Xuzheng Wang Avatar asked Mar 10 '16 07:03

Xuzheng Wang


1 Answers

This code fails in Java-7, but compiles in Java-8. Using javac 7u80 I see:

Main.java:7: error: incompatible types
                List<Snow> snow = Arrays.asList(new Light(), new Heavy());
                                               ^
  required: List<Snow>
  found:    List<Powder>
1 error

The type inference in Java-8 was significantly improved. Prior to that the type was inferred for every sub-expression exclusively based on the analysis of that sub-expression, so the type of Arrays.asList(new Light(), new Heavy()) was required to be known regardless of the surrounding context. In Java-8 the surrounding context may account to the expression type.

In Java Language Specification version 8 there's a whole new chapter dedicated to the type inference. It's not very easy to read, but to my understanding now instead of assigning the concrete type to every subexpression a set of constraints is assigned. In our case the constraints are Light <: T && Heavy <: T (no exact type is inferred here). Next the reduction process is performed which reduces the set of constraints to the set of bounds taking into account expression compatibility constraints.

like image 76
Tagir Valeev Avatar answered Oct 23 '22 10:10

Tagir Valeev