Write a generic class Pair which has two type parameters—F and S—each representi
ID: 3591794 • Letter: W
Question
Write a generic class Pair which has two type parameters—F and S—each representing the type of the first and second element of the pair, respectively. Add set and get methods for the first and second elements of the pair. (Hint: The class header should be public class Pair.)
Write a separate PairTest class to test class Pair. Create 2 Pair types and test your get and set methods on the following pair types:
Pair p1 takes Integer and String types as a pair
Pair p2 takes String and Integer
PairTest should output enough information to the terminal to show that your generic class Pair is able to set() and get() different types.
Explanation / Answer
/** ~~~~Tried in eclipse with JUnit4 ~~~~~~~~~~~*/
/** ~~~~~class Pair.java ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ */
public class Pair<F,S> {
private F f;
private S s;
/** Setter and getters */
public F getF(){
return this.f;
}
public void setF(F f1){
this.f = f1;
}
public S getS(){
return this.s;
}
public void setS(S s1){
this.s = s1;
}
/**~~~~~~~~~~ PairTest.java ~~~~~~~~~~~~*/
import org.junit.Test;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import Pair;
public class PairTest<F , S>{
private static Logger log = LoggerFactory.getLogger(PairTest.class);
@Test
public void testPair(){
// p1 is of type String, Integer
Pair p1 = new Pair();
p1.setF("Six");
p1.setS(6);
// p1 is of type Integer, String
Pair p2 = new Pair();
p2.setF(7);
p2.setS("Seven");
log.info("[p1 output:]"+ "F value: " + p1.getF() + ", F type:" + p1.getF().getClass() + ", S value:" + p1.getS() + ", S type:" + p1.getF().getClass());
log.info("[p2 output:]"+ "F value: " + p2.getF() + ", F type:" + p2.getF().getClass() + ", S value:" + p2.getS() + ", S type:" + p2.getF().getClass());
}
}
}
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.