2014-05-01 71 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