Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    primarykey
    data
    text
    <p>You could of course use wrapper methods to add elements to the map, and do a check for Integer and Sring there. But then you only get runtime errors. I agree with you that restricting the type to get static errors is much better.</p> <p>For that, I would actually not use Integer.class and String.class, but an enum:</p> <pre><code>enum Types { String, Integer }; private Map&lt;String, Types&gt; attributeList = new HashMap&lt;String, Types&gt;(); </code></pre> <hr> <p>UPDATE:</p> <p>Come to think of it, there is another (but more complicated) solution, if you <strong>have</strong> to stick to Class objects: You can use the fake enum pattern, that is use a set of constants (usually the integers 2^i are used) like an enum. So you could define your Class objects as the constants. That of course does not guarantee that no other class objects are put into the map. That's why Joshua Bloch item 30 says "Use enums instead of int constants". <strong>But</strong> you can then use the <a href="https://checkerframework.org/" rel="nofollow noreferrer">Checker Framework</a> to pull an additional type system over your constants using the Fake Enum checker:</p> <pre><code>@SuppressWarnings("fenum:assignment.type.incompatible") public class TypeEnum { public static final @Fenum("Types") Class INT_CONST = Integer.class; public static final @Fenum("Types") Class STR_CONST = String.class; } </code></pre> <p>Then you can define your map with a restriction on the type Class:</p> <pre><code>private HashMap&lt;String, @Fenum("Types") Class&gt; attributeList = new HashMap&lt;String, @Fenum("Types") Class&gt;(); </code></pre> <p>Of course, you would need to include the <a href="https://checkerframework.org/manual/#fenum-checker" rel="nofollow noreferrer">Fenum Checker</a> into your compiler.</p>
    singulars
    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. VO
      singulars
      1. This table or related slice is empty.
    2. VO
      singulars
      1. This table or related slice is empty.
    3. VO
      singulars
      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