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

Write a simple generic version of method isEqualTo that compares its two argumen

ID: 3642061 • Letter: W

Question

Write a simple generic version of method isEqualTo that compares its two arguments with the equals method and returns true if they are equal and false otherwise. Use this generic method in a program that calls isEqualTo with a variety of built-in types, such as Object or Integer.

here is the code the teacher provided


// Fig. 21.3: GenericMethodTest.java
// Printing array elements using generic method printArray.

public class GenericMethodTest
{
public static void main( String[] args )
{
// create arrays of Integer, Double and Character
Integer[] integerArray = { 1, 2, 3, 4, 5, 6 };
Double[] doubleArray = { 1.1, 2.2, 3.3, 4.4, 5.5, 6.6, 7.7 };
Character[] characterArray = { 'H', 'E', 'L', 'L', 'O' };

System.out.println( "Array integerArray contains:" );
printArray( integerArray ); // pass an Integer array
System.out.println( " Array doubleArray contains:" );
printArray( doubleArray ); // pass a Double array
System.out.println( " Array characterArray contains:" );
printArray( characterArray ); // pass a Character array
} // end main

// generic method printArray
public static < T > void printArray( T[] inputArray )
{
// display array elements
for ( T element : inputArray )
System.out.printf( "%s ", element );

System.out.println();
} // end method printArray
} // end class GenericMethodTest

Explanation / Answer

public class IsEqual {

       public static void main(String[] args) {

              Object>new Object();

              Object two = one;

              if(isEqualTo(one,two)) {

                     System.out.println("Objects one and two are equal");

              }

              Object three = new Object();

              if(isEqualTo(one,three)) {

                     System.out.println("Objects one and three are equal");

              }

              int four = 5;

              int five = 5;

              if(isEqualTo(four,five)) {

                     System.out.println("5 is equal to 5");

              }

              int six = 17;

              if(isEqualTo(four,six)) {

                     System.out.println("5 is equal to 17");

              }

       }

       public static <T> boolean isEqualTo(T arg1, T arg2) {

              return arg1.equals(arg2);

       }

}

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