I have a question about generics in Java, i.e. using wildcards I have an example class GenClass like this:
Public Class GenClass & lt; E & gt; {Private E var; Public Zero Set-up (E x) {var = x; } Public e getVar () {return var; }}
I have another simple class:
public class ExampleClass {}
I wrote the following Test class:
public square test genclass {public static zero main (string [] str) {example class EC = new example class (); GenClass & LT; ExampleClass & gt; C = new GenClass & lt; ExampleClass & gt; (); C.setVar (EC); Println (c.getVar ()); // Output: ExampleClass @ addbf1}} Now, if I use wildcard and write it in the test class: GenClass & lt ;? & Gt; C = new GenClass & lt; ExampleClass & gt; (); At the place of
:
GenClass & lt; ExampleClass & gt; C = new GenClass & lt; ExampleClass & gt; ();
The compiler does not have any problems with this new statement, however, there is a complaint about
c.setVar (ec);
It says, "The method (Setter ()) is not applicable for argument (example class)". Why do I get this message?
I thought that the way I have used wildcards, the type of reference variable creates a G class, which will accept any class as the parameter of any class in place of EM Only the variable is declared then I'll call it
New GenClass & lt; ExampleClass & gt; I am starting with ()
which means that I will create a square of an object which has the type of parameter which is a class of GenClass, eg ExampleClass, I think now E would be an ExampleClass in GenClass, and I would be able to use the method setVar (), giving this example as the exampleClass argument. It was my perception and understanding, but it seems that Java does not like it, and I am not right. Any comments are appreciated, thanks.
This is included in this exact situation.
Note that [with wildcard], we can still read the element from [normal
archive
] and by typing themobject
You can. It is always safe, because whatever the actual type of archive contains objects in it, though it is not safe to add arbitrary items:
archive
Since we do not know what type of
c
element, we can not add objects to itadd ( )
takes argument type methode
, the element type of the collection. When the actual type parameter?
, then it stands for some unknown type. Any parameters passing throughaddition
should be a subtype of this unknown type. Since we do not know what kind, we can not give anything. The only exception iszero
, which is a member of every type.
(emphasis my)
Comments
Post a Comment