Write a generic class Pair which has 2 type parameters, F and S, representing th
ID: 3823327 • Letter: W
Question
Write a generic class Pair which has 2 type parameters, F and S, representing the type of the first and second elements of a pair respectively. Add get and set methods for the first and second elements of the pair. Override the toString() method to display the first and second values of the pair in a format of your choosing. Use the Pair class in a program that creates an ArrayList of 10 Pair objects containing values of your choosing. The program will then print the string representation of each Pair to System.out (i.e., use the toString() method).
Explanation / Answer
Ans:
// pair class
public class Pair< F, S >
{
//F
private F first;
// S
private S second;
// pair
public Pair( F element1, S element2)
{
// first
first= element1;
// second
second= element2;
}
//getFirst
public F getFirst()
{
// return
return first;
}
//second
public S getSecond()
{
return
return second
}
// setFirst
public void setFirst( F element1 )
{
// elemnt 1
first = element1 ;
// set second
} public void setSecond( S element2 )
{
// elmnt 2
second = element2 ;
}
}
driver program:
public class Driver
{
// main
public static void main( String args[] )
{
// pair,--4, first
Pair< Integer, String > numberPair = new Pair< Integer, String >( 4, "First");
System.out.printf( "First pair: < %d, %s > ", numberPair.getFirst(), numberPair.getSecond() );
// setFirst(5)
numberPair.setFirst( 5 );
// secoind()
numberPair.setSecond( "Second" );
// prints op
System.out.printf( "Second pair: < %d, %s > ", numberPair.getFirst(), numberPair.getSecon());
}
}
// thank you//
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.