5

This is from Thinking in Java

class Snow {}
class Powder extends Snow {}
class Light extends Powder {}
class Heavy extends Powder {}
class Crusty extends Snow {}
class Slush extends Snow {}

public class AsListInference {
    public static void main(String[] args) {
        //The book says it won't compile, but actually it does.
        List<Snow> snow2 = Arrays.asList(new Light(), new Heavy());
    }
}

Here is my Java enviroment:

  1. java version "1.8.0_60"
  2. Java(TM) SE Runtime Environment (build 1.8.0_60-b27)
  3. Java HotSpot(TM) 64-Bit Server VM (build 25.60-b23, mixed mode)
2
  • 3
    Because there should not be one. Light and Heavy are subclasses of Snow, and can therefore be added to a List of Snow. Commented Oct 17, 2015 at 11:05
  • 1
    In Java 7 this code gives me a compilation error - Type mismatch: cannot convert from List<Powder> to List<Snow>. Commented Oct 17, 2015 at 11:09

2 Answers 2

6

Actually, the book is right. The difference here is the Java version.

Thinking in Java targets Java 5/6 (as per the cover). For this version of Java (and with Java 7 also), the snippet won't compile with javac. The error is:

incompatible types: java.util.List<Powder> cannot be converted to java.util.List<Snow>

With Java 8, this compiles just fine: the type-inference system was improved.

Sign up to request clarification or add additional context in comments.

Comments

2

The book is apparently expecting the compiler to determine the type of the right-hand side as List<Powder>, which is not a List<Snow>. However, since Arrays.<T>asList(T ...) has its own self-contained scope for T, the compiler is able to infer that the correct bound should be Snow and that both Light and Heavy are Snow.

I don't have a Java 7 compiler on hand, but Java 8 did bring some improvements in generic type inference that may be what lets the compiler solve this particular type bound.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.