
Question:
I have the following class <strong>AccountWebappGridRow</strong>, which extends <strong>AccountGridRow</strong>:
public class AccountWebappGridRow<Accounts> extends AccountGridRow implements java.io.Serializable {
<strong>AccountGridRow</strong> contains has this field:
private Map<Integer, Integer> balances;
With <strong>public</strong> getters/setters:
public Map<Integer, Integer> getBalances() {
return balances;
}
public void setBalances(Map<Integer, Integer> balances) {
this.balances = balances;
}
Is there a way that I can somehow override/replace the inherited
private Map<Integer, Integer> balances;
in my <strong>AccountWebappGridRow</strong>...with this instead:
private Map<String, Integer> balances;
Answer1:Sure. You can do that ... as soon as <strong>you</strong> can provide a mapping that will allow you to turn an <strong>Integer</strong> key into a String key.
In other words: your class knows about Integer keys and values. Of course you can now add another map that uses the same values. The only thing required is that <strong>you</strong> create a <em>meaningful</em> mapping function. <em>Meaningful</em> meaning: a function that fits <em>your</em> requirements. We don't know what content the Map<String, Integer>
is supposed to hold; so we can't tell you how to properly map keys here!
The most simple answer could be to use
String stringKey = someIntegerKey.toString();
resp.
Integer integerKey = Integer.parseString(stringKey);
With those <em>mappings</em> you can now take the <em>internal</em> map and create a "result" map that uses Integers again.
In other words: you can add that new map to your class; or you can completely rework your class and change that balances
field to use a different key. All of that is just "work" - and all of that relies on <em>you</em> defining how you get from Integer to String keys; and vice versa.
you can define a method that using stream turn the Map<Integer, Integer>
into a Map<String, Integer>
public Map<String, Integer> getBalancesStringString() {
return balances.entrySet()
.stream()
.collect(Collectors.toMap(e -> e.toString(), e -> e.getValue()));
}