Generic pair class

后端 未结 14 1689
情话喂你
情话喂你 2020-12-01 16:49

Just attempting this question I found in a past exam paper so that I can prepare for an upcoming Java examination.

Provide a generic class Pair for representing pair

14条回答
  •  情话喂你
    2020-12-01 17:07

    I implemented something similar but with static builder and chained setters

    public class Pair {
    
    private R left;
    private L right;
    
    public static  Pair of(K k, V v) {
        return new Pair(k, v);
    }
    
    public Pair() {}
    
    public Pair(R key, L value) {
        this.left(key);
        this.right(value);
    }
    
    public R left() {
        return left;
    }
    
    public Pair left(R key) {
        this.left = key;
        return this;
    }
    
    public L right() {
        return right;
    }
    
    public Pair right(L value) {
        this.right = value;
        return this;
    }
    }
    

提交回复
热议问题