Question: Using the code below: Override the toString() method to display the first and second values of the pair in a format of your choosing. Use

Using the code below: 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).

public class Pair< F, S >

{

private F first; // first element of a pair

private S second; // second element of a pair

// constructor

public Pair( F firstElement, S secondElement )

{

first = firstElement;

second = secondElement;

} // end Pair constructor

// get first

public F getFirst()

{

return first;

} // end method getFirst

// get second

public S getSecond()

{

return second;

} // end method getSecond

// set first

public void setFirst( F firstElement )

{

first = firstElement;

} // end method setFirst

// set second

public void setSecond( S secondElement )

{

second = secondElement;

} // end method setSecond

} // end class Pair

// Generic Pair class testing program.

public class PairTest

{

public static void main( String args[] )

{

// create pair of integer and string

Pair< Integer, String > numberPair =

new Pair< Integer, String >( 1, "one" );

// display original numberPair

System.out.printf( "Original pair: < %d, %s > ",

numberPair.getFirst(), numberPair.getSecond() );

// modify pair

numberPair.setFirst( 2 );

numberPair.setSecond( "Second" );

// display modified numberPair

System.out.printf( "Modified pair: < %d, %s > ",

numberPair.getFirst(), numberPair.getSecond() );

} // end method main

} // end class PairTest

Step by Step Solution

There are 3 Steps involved in it

1 Expert Approved Answer
Step: 1 Unlock blur-text-image
Question Has Been Solved by an Expert!

Get step-by-step solutions from verified subject matter experts

Step: 2 Unlock
Step: 3 Unlock

Students Have Also Explored These Related Databases Questions!