Academic Integrity: tutoring, explanations, and feedback — we don’t complete graded work or submit on a student’s behalf.

Write a generic class Pair which has two type parameters—F and S—each representi

ID: 3838993 • 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<F, S>.)

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<Integer, String> p1 takes Integer and String types as a pair

Pair<String, Integer> 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

public class Pair<F, S> {
    private F First;
    private S Second;

    public Pair( F f, S s ) {
        First = f;
        Second = s;
    }

    public F get_first() { return First; }
    public S get_second() { return Second; }
    public void set_first( F f ) { First = f; }
    public void set_second( S s ) { Second = s; }
    public String toString( ) { return + First +","+ Second + ; }
}


class TestPair {
    static public void main( String[] args ) {
        Pair<int, int> pair1 = null, pair2 = null;

        pair1 = new Pair<int, int>( 1, 2 );
        pair2 = new Pair<int, int>( 3, 4 );

        System.out.println( "pair1 is:" + pair1 );
        System.out.println( "pair2 is: " + pair2 );
        pair1.set_first( pair2.get_second() );

        System.out.println( "pair1 = " + pair1 );
    }
}

Hire Me For All Your Tutoring Needs
Integrity-first tutoring: clear explanations, guidance, and feedback.
Drop an Email at
drjack9650@gmail.com
Chat Now And Get Quote