【问题标题】:How to access to a hashmap keyset with arraylist如何使用 arraylist 访问 hashmap 键集
【发布时间】:2017-02-23 10:01:58
【问题描述】:

实际上,每次我想要一个键的位置时,我都会创建一个 LinkedHashMap 的键集的新 ArrayList。

public static Map<Integer, Object> ObjectsWithId = new LinkedHashMap<>();


public int getId(int number) {
     return (number <= ObjectsWithId.size()) ? new ArrayList<Integer>(ObjectsWithId.keySet()).get(number-1) : -1;
}

有没有办法用 ArrayList 创建 HashMap 的键集的“链接”? 我不希望每次我想要一个键的位置时都创建一个 ArrayList。

这是我尝试过的以及我想要的:

public static Map<Integer, Object> ObjectsWithId = new LinkedHashMap<>();
public static ArrayList<Integer> ObjectsKeys = new ArrayList<Integer>(ObjectsWithId.keySet());

public int getId(int number) {
         return (number <= ObjectsWithId.size()) ? ObjectsKeys.get(number-1) : -1;
}

提前致谢。 :)

【问题讨论】:

    标签: java arraylist hashmap linkedhashmap keyset


    【解决方案1】:

    如果你的动机是创建对象的轻量级,你可以考虑创建一个数组。

    public int getId(int index) {
         return (index <= ObjectsWithId.size()) ? (int) ObjectsWithId.keySet().toArray()[index-1] : -1;
    }
    

    顺便说一句:考虑将 number 参数重命名为 index,因为这是(我认为)您的意图。

    【讨论】:

      【解决方案2】:

      用for循环怎么样?

      如果你不想创建 ArrayList 你可以试试下面的一个。

      public int getId( int number ) {
          int position = 0;
          int i = 0;
      
          for ( Map.Entry<Integer, Object> entry : ObjectsWithId.entrySet() ) {
              if ( number == entry.getKey() ) {
                  position = i;
      
                  break;
              } else {
                  i++;
              }
          }
          return position;
      }
      

      【讨论】:

        猜你喜欢
        • 2019-11-01
        • 1970-01-01
        • 1970-01-01
        • 2011-09-13
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2021-11-20
        • 2016-02-13
        相关资源
        最近更新 更多