Domanda

I have a simple class below which when compiled autoboxes the Integer correctly But, fails to do it for my Boolean it insists that I should change the parameter to a boolean. I am using jdk 1.8 otherwise the compiler would have complained about the Integer conversion. I cannot see what I am doing wrong ? All wrapper classes can autobox out of the box or so I thought ?

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

    }

}

And is it not the case that Autoboxing is a two way process ?

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
È stato utile?

Soluzione

Your problem is the first line:

public class MsgLog<Boolean,String> 

You are declaring type parameters named "Boolean" and "String". These are shadowing the actual Boolean and String types. You don't even need type parameters for this class, as far as I can see; just remove them. If you do want to keep them, you should rename them to avoid shadowing the existing types.

Semantically, the code you posted is equivalent to (with some snipped for brevity):

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 ;
    }

}
Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top