How to use two numbers as a Map key

前端 未结 8 2026
天命终不由人
天命终不由人 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:50

    You can store two integers in a long like this,

       long n = (l << 32) | (r & 0XFFFFFFFFL);
    

    Or you can use following Pair class,

    public class Pair {
    
        private L l;
        private R r;
    
        public Pair() {
        }
    
        public Pair(L l, R r) {
            this.l = l;
            this.r = r;
        }
    
        public L getLeft() {
            return l;
        }
    
        public R getRight() {
            return r;
        }
    
        @Override
        public boolean equals(Object o) {
            if (!(o instanceof Pair)) {
                return false;
            }
            Pair obj = (Pair) o;
            return l.equals(obj.l) && r.equals(obj.r);
        }
    
        @Override
        public int hashCode() {
            return l.hashCode() ^ r.hashCode();
        }
    } 
    

提交回复
热议问题