gpt4 book ai didi

java - 定义 map 、集合等,然后传递/获取它们

转载 作者:塔克拉玛干 更新时间:2023-11-02 20:06:15 26 4
gpt4 key购买 nike

我读到当你定义一个 {Map, Set, Etc} 时,最好使用 interface 名称:

Map<Integer, String> map = new LinkedHashMap<Integer, String>();

代替:

LinkedHashMap<Integer, String> map = new LinkedHashMap<Integer, String>();

我不确定这是为什么,但我已经将其付诸实践,希望以后能理解。也许那个时候到了。

所以我创建了一个定义一个的类,并为 Map 创建了一个 getter:

class Data{

private Map<Integer, String> map;

public Data(){
map = new LinkedHashMap<Integer, String>();
//dynamically put some things into the map
}

public Map<Integer, String> getMap(){
return map;
}

}

现在我遇到了第一个僵局。我不能返回一个 LinkedHashMap,我必须返回一个 Map。所以在另一个类中我得到了 Map

class Foo{

public Foo{
Data data = new Data();
Map<Integer, String> map = data.getMap();
}

}

  • 有人可以解释 map 通过时发生了什么吗?
  • 它还是一个LinkedHashMap吗?
  • 数据有变化吗?
  • 如果在调用 getData() 之后,我在 Map 中添加了一些内容,Map 的顺序会发生什么变化>?
  • 为什么我不能/不应该像在第二个代码片段中那样定义 map ?
    我做 map 的方法是无知的吗?
  • 我应该只公开 map 吗?

  • 最佳答案

    Now I come to my first impasse. I can't return a LinkedHashMap

    这是一个误解:您可以返回一个LinkedHashMap,因为LinkedHashMap 一个Map ,一种特殊的 Map,但无论如何都是 Map

    Can someone explain what is happening to map when it gets passed?

    当它通过时,它被视为任何 Map,如 incognito,但它保持不变。

    Is it still a LinkedHashMap?

    是的。

    Is the data changed at all?

    没有。

    What would happen to the order of the Map if, after calling getData(), I put something in the Map?

    这是另一个话题。

    Why wouldn't/shouldn't I just define the Map as in the second code snippet?

    你不需要这样做,因为 LinkedHashMap 是一个 Map(另一方面,一个 Map 不一定是 LinkedHashMap)。

    Is my method of getting the map done in ignorance? Should I just make map public?

    没有。

    关于java - 定义 map 、集合等,然后传递/获取它们,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21117827/

    26 4 0
    Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
    广告合作:1813099741@qq.com 6ren.com