Note that there are some explanatory texts on larger screens.

plurals
  1. POHow to avoid unsafe cast warnings with Java Generics
    primarykey
    data
    text
    <p>I'm quite new to Java Generics. But I've read a lot of summary links and examples. But I cannot get the simplest method right. I hope somenoe can help:</p> <p>I want to create a HashMap which maps one undefined Object to another one. Both objects may one of String or Integer.</p> <p>So I wrote this:</p> <pre><code>private final HashMap&lt;L, R&gt; left2Right = new HashMap&lt;L, R&gt;(); Extractor&lt;?&gt; extLeft = Extractor.getInstance(0); Extractor&lt;?&gt; extRight = Extractor.getInstance(1); L leftVal = extLeft.extract(d, i); R rightVal = extRight.extract(d, i); this.left2Right.put(leftVal, rightVal); </code></pre> <p>So far so good... But I have problems implementing the extractor-objects. They are instanciated by a factory pattern. I did it like this (simplyfied):</p> <pre><code>abstract class Extractor&lt;E&gt; { abstract E extract(DTable source, int row); static &lt;E&gt; Extractor&lt;E&gt; getInstance(int type) { if(type == 0) return new IntExtractor(); else return new StringExtractor(); } } class IntExtractor extends Extractor&lt;Integer&gt; { @Override Integer extract(DTable source, int row) { int value = 5; return new Integer(value); } } class StringExtractor extends Extractor&lt;String&gt; { @Override String extract(DTable source, int row) { String retVal = "hello"; return retVal; } } </code></pre> <p>It compiles, but I get Unsave cast warnings on casting the Integer/String to E. What am I doing wrong? I know, I can simply supress the warnings. But I thought exactly this should be the advantage of Java generics? I cannot make this cast save, because I dont know, which type 'E' really "is"...</p> <p>Or am I doing something basically wrong?</p> <p>Note: I edited my code to a "new" question after I used some information from the first answer...</p>
    singulars
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload