How to use two numbers as a Map key

前端 未结 8 1981
天命终不由人
天命终不由人 2020-12-17 20:32

I have two numbers and I want to use them together as a key in a Map. Currently, I\'m concatenating their string representations. For example, suppose the key n

8条回答
  •  無奈伤痛
    2020-12-17 20:52

    Create an object that holds the two numbers and use it as the key. For example:

    class Coordinates {
    
      private int x;
      private int y;
    
      public Coordinates(int x, int y) {
         ...
      }
    
      // getters
    
      // equals and hashcode using x and y
    }
    
    Map locations = new HashMap();
    

    If you prefer a mathematical approach, see this StackOverflow answer.

提交回复
热议问题