自动装箱不适用于布尔值

时间:2014-05-01 13:46:45

标签: java boolean autoboxing

我在下面有一个简单的类,当编译时正确地自动装箱整数 但是,没有为我的布尔做它它坚持我应该将参数更改为布尔值。我正在使用jdk 1.8否则编译器会抱怨Integer转换。我看不出我做错了什么?所有包装类都可以开箱即用,或者我认为?

public class MsgLog<Boolean,String> {

    private boolean sentOk ;
    private Integer id ;
    private int id2 ;
    public boolean isSentOk() {
        return sentOk;
    }

    public String getTheMsg() {
        return theMsg;
    }

    private String theMsg ;

    private MsgLog(Boolean sentOkp, String theMsg)
    {

        this.sentOk = sentOkp ; // compile error - autoboxing not working

        this.theMsg = theMsg ;

        this.id = 2; // autoboxing working
        this.id2 = (new Integer(7)) ; // autoboxing working the other way around as well

    }

}

并非Autoboxing是一个双向过程的情况吗?

Compile error on jdk 8 (javac 1.8.0_25)
Multiple markers at this line
    - Duplicate type parameter String
    - The type parameter String is hiding the type String
    - The type parameter Boolean is hiding the type 
     Boolean

1 个答案:

答案 0 :(得分:6)

你的问题是第一行:

public class MsgLog<Boolean,String> 

您正在声明名为“Boolean”和“String”的类型参数。这些会影响实际的BooleanString类型。就我所见,你甚至不需要这个类的类型参数;只是删除它们。如果您确实要保留它们,则应重命名它们以避免遮蔽现有类型。

从语义上讲,您发布的代码相当于(为简洁而剪裁了一些代码):

public class MsgLog<T,U> {

    private boolean sentOk ;
    private U theMsg ;

    private MsgLog(T sentOkp, U theMsg)
    {

        this.sentOk = sentOkp ; // compile error - assignment to incompatible type
        this.theMsg = theMsg ;
    }

}
相关问题