Note that there are some explanatory texts on larger screens.

plurals
  1. POHow to avoid casting for wrapper objects in maps?
    primarykey
    data
    text
    <p>I have an interface FeatureValue which implements a function called pretty print.</p> <p>I have two classes right now that implement that interface: FeatureString and FeatureList (The lists in FeatureList contain strings). These classes are just wrapper that store a string and a list respectively and implement the pretty print function for their wrapped values.</p> <p>I have EnumMap which takes as keys some enums of type Feature (some which correspond to strings and some which correspond to lists). </p> <p>I originally made this interface so that I could just iterate over the Enums and pretty print them. But now I want to be able to get the value from the wrapper FeatureValue as well. </p> <p>Since I'm storing the enum map as <code>&lt;Feature, FeatureValue&gt;</code> , it doesn't know what type the wrapped value is so I have to cast when I get it. </p> <p>Is there a way to refactor my code so that I don't need to cast, but still retain the ability to just iterate over the Enums and print them without knowing the type?</p> <p>Enum</p> <pre><code>public enum Features { KIND("kind"), RULE("rule"), PROBLEM("problem"), private String name; Features(String name) { this.name = name; } public String getName() { return name; } } </code></pre> <p>Interface</p> <pre><code>public interface FeatureValue { public String prettyPrint(); } </code></pre> <p>List implementation (There's a similar one for FeatureString which I'll omit)</p> <pre><code>public class FeatureList implements FeatureValue { private final List&lt;String&gt; list; public FeatureList(List&lt;String&gt; list) { this.list = list; } @Override public String prettyPrint() { return Arrays.toString(list.toArray()); } public List&lt;String&gt; getList() { return list; } } </code></pre> <p>Casting code</p> <pre><code>for(String token: ((FeatureList) enumMap.get(Feature.particularFeatureThatCorrespondsToLists)).getValue()) doSomething(token); </code></pre> <p>There is a cast necessary since the map is parameterized for values of Feature, not FeatureList</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