javagenericsgeneric-programming

Generic pair class


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 pairs of things. The class should provide a constructor, a method for getting the first member of the pair, a method for getting the second member of the pair, a method for setting the first member of the pair, a method for setting the second member of the pair. The class should be parameterised over two types one for the first member and one for the second member of the pair.

Is this a correct implementation for this question ?

public class Pair<firstThing, secondThing>{
   private firstThing first;//first member of pair
   private secondThing second;//second member of pair

   public Pair(firstThing first, secondThing second){
     this.first = first;
     this.second = second;
   }

   public void setFirst(firstThing first){
    this.first = first;
   }

   public void setSecond(secondThing second) {
     this.second = second;
   }

   public thing getFirst() {
     return this.first;
   }

   public thing getSecond() {
     return this.second;
   }
}

Solution

  • Almost. I'd write it like this:

    public class Pair<F, S> {
        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.