In: Computer Science
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
Pair
PairTest should output enough information to the terminal to show that your generic class Pair is able to set() and get() different types.
Pair.java
public class Pair
private F first;
private S second;
/**
* @return the first element
*/
public F getFirst() {
return first;
}
/**
* @param first the element first to set
*/
public void setFirst(F first) {
this.first = first;
}
/**
* @return the second element
*/
public S getSecond() {
return second;
}
/**
* @param second the element second to set
*/
public void setSecond(S second) {
this.second = second;
}
}
PairTest.java
public class PairTest {
/**
* @param args
*/
public static void main(String[] args) {
/*Instance of Generic class Pair
with parameters F-String and S-Integer*/
Pair
p1.setFirst("Java");
p1.setSecond(10);
System.out.printf("The elements for
First Pair are %s and %d.\n", p1.getFirst(),p1.getSecond());
/*Instance of Generic class Pair
with parameters F-Integer and S-String*/
Pair
p2.setFirst(20);
p2.setSecond("Python");
System.out.printf("The elements
for Second Pair are %d and %s.",
p2.getFirst(),p2.getSecond());
}
}
Output