有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

java我可以用Map<String,Integer>覆盖Map<Integer,Integer>吗?

我有以下类AccountWebappGridRow,它扩展了AccountGridRow

public class AccountWebappGridRow<Accounts> extends AccountGridRow implements java.io.Serializable {

AccountGridRow包含以下字段:

private Map<Integer, Integer> balances;

对于公众能手/二传手:

public Map<Integer, Integer> getBalances() {
  return balances;
}

public void setBalances(Map<Integer, Integer> balances) {
   this.balances = balances;
}

有没有一种方法可以让我以某种方式覆盖/替换继承的

private Map<Integer, Integer> balances;

在我的账户webappgridrow。。。换言之:

private Map<String, Integer> balances;

共 (2) 个答案

  1. # 1 楼答案

    当然。你可以这么做。。。只要就可以提供一个映射,允许你将整数键转换成字符串键

    换句话说:你的类知道整数键和值。当然,现在可以添加另一个使用相同值的贴图。唯一需要做的就是创建一个有意义的映射函数有意义的意义:符合您的要求的功能。我们不知道Map<String, Integer>应该包含什么内容;所以我们不能告诉你如何正确地在这里映射键

    最简单的答案可能是使用

    String stringKey = someIntegerKey.toString();
    

    响应

    Integer integerKey = Integer.parseString(stringKey);
    

    有了这些映射你现在可以使用内部映射并创建一个再次使用整数的“结果”映射

    换句话说:你可以将新地图添加到你的类中;或者,您可以完全修改类,并更改balances字段以使用不同的键。所有这些都只是“工作”——所有这些都依赖于定义如何从整数键到字符串键;反之亦然

  2. # 2 楼答案

    您可以定义一个方法,使用stream将Map<Integer, Integer>转换为Map<String, Integer>

    public Map<String, Integer> getBalancesStringString() {
        return balances.entrySet()
                .stream()
                .collect(Collectors.toMap(e -> e.toString(), e -> e.getValue()));
    }