Generic pair class

后端 未结 14 1696
情话喂你
情话喂你 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:14

    Almost. I'd write it like this:

    public class Pair {
        private F first; //first member of pair
        private S second; //second member of pair
    
        public Pair(F first, S second) {
            this.first = first;
            this.second = second;
        }
    
        public void setFirst(F first) {
            this.first = first;
        }
    
        public void setSecond(S second) {
            this.second = second;
        }
    
        public F getFirst() {
            return first;
        }
    
        public S getSecond() {
            return second;
        }
    }
    

    Edit: I agree with @karmakaze's comment. The code should skip the setters and make first and second final to keep it immutable.

提交回复
热议问题