Create an application that provides a solution for problem 20.8 In addition to requirements specified in the description. The class must satisfy the following
Default Constructor
Two argument constructor for data used to initialize "first" and "second"
"toString" method for displaying the "first" and "second" data elements
Creates a "Comparator" object (to be used by the sort method; i.e. create an instance of a class that implements the interface [must override "compare" and "equals" methods])
The application must create an ArrayList of 5 Pair objects and then display the contents in sorted order largest to smallest, based on the method used to compare "Pair" objects. The class only supports types that extend Number. Assume the "Pair" objects contain x, y coordinates. Therefore calculate the distance from a 0,0 coordinate to detrmine the sorting order (i.e., ascending, smallest distance to largest distance).
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
// Exercise 18.8 Solution: PairTest.java
// 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 >\n",
numberPair.getFirst(), numberPair.getSecond() );
// modify pair
numberPair.setFirst( 2 );
numberPair.setSecond( "Second" );
// display modified numberPair
System.out.printf( "Modified pair: < %d, %s >\n",
numberPair.getFirst(), numberPair.getSecond() );
} // end method main
} // end class PairTest
Attachment:- application.png