2014-05-01 66 views
0

我有一个简单的类下面编写自动包装整数正确 但是,无法为我的布尔它坚持我应该改变参数为布尔值。我使用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 

    } 

} 

是不是自动装箱是一种双向过程?

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 
+2

你可能会考虑分享实际的编译器错误,而不是让我们猜... – evanchooly

+3

有没有拳击的一切会在行'this.id = 2;'这样你的评论“autoboxing工作”是不正确的。 – Jesper

回答

6

您的问题是第一行:

public class MsgLog<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 ; 
    } 

} 
+0

+1,具体而言,它们是_generic_类型参数,这可能有助于阐明OP。 – GriffeyDog

+1

@GriffeyDog谢谢,但这些类型参数是不是通用的(相反,它们是泛型类型的类型参数)!在这种情况下,术语“类型参数”是正确的。就我所见,语言规范甚至不使用术语“泛型类型参数”。见例如http://docs.oracle.com/javase/specs/jls/se7/html/jls-8.html#jls-8.1.2 – davmac

+0

我可以用更好的措辞。它们是_generic class_的类型参数。 – GriffeyDog