Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why is there no type conversion exception in this code?

Tags:

java

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)
like image 818
user2916610 Avatar asked Oct 17 '15 11:10

user2916610


People also ask

How do I fix incompatible type error?

Swapping the inappropriate constructor call with an instance of the correct type solves the issue, as shown in Fig. 6(b). Fig. 6 also serves as an example to show how the incompatible types error is, in fact, a generalization of the method X in class Y cannot be applied to given types error explored in [4].

What does Java Util IllegalFormatConversionException mean?

The IllegalFormatConversionException is an unchecked exception in Java that occurs when the argument that corresponds to a format specifier is of an incompatible type. Since the IllegalFormatConversionException is thrown at runtime, it does not need to be declared in the throws clause of a method or constructor.

What is type conversion and casting in Java?

In type casting, a data type is converted into another data type by a programmer using casting operator. Whereas in type conversion, a data type is converted into another data type by a compiler.

Is illegal class format exception checked or unchecked?

Class IllegalFormatExceptionUnchecked exception thrown when a format string contains an illegal syntax or a format specifier that is incompatible with the given arguments. Only explicit subtypes of this exception which correspond to specific errors should be instantiated.


1 Answers

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.

like image 130
Tunaki Avatar answered Oct 27 '22 11:10

Tunaki