Java Generics Hackerrank Solution

Java Generics Hackerrank Solution
Java Generics Hackerrank Solution

Java Generics Hackerrank Solution

Generic methods are a very efficient way to handle multiple datatypes using a single method. This problem will test your knowledge on Java Generic methods.

Let’s say you have an integer array and a string array. You have to write a single method printArray that can print all the elements of both arrays. The method should be able to accept both integer arrays or string arrays.

You are given code in the editor. Complete the code so that it prints the following lines:


Do not use method overloading because your answer will not be accepted.

//Java Generics Hackerrank Solution
import java.lang.reflect.Method;
class Printer
   //Write your code here
public static <E> void printArray(E[] inputArray )
for (E element : inputArray)
      System.out.printf("%s\n", element);
public class Solution {
    public static void main( String args[] ) {
        Printer myPrinter = new Printer();
        Integer[] intArray = { 1, 2, 3 };
        String[] stringArray = {"Hello", "World"};
        int count = 0;
        for (Method method : Printer.class.getDeclaredMethods()) {
            String name = method.getName();
        if(count > 1)System.out.println("Method overloading is not allowed!");
//Java Generics Hackerrank Solution

This Java code is a solution to a problem on HackerRank related to generics. Let’s break down the code and explain each part:

  1. The Printer class:
    • This class contains a static method printArray which is a generic method. It takes an array of type E as input and prints each element of the array.
  2. The Solution class:
    • This is the main class which contains the main method, serving as the entry point of the program.
    • Inside main, an instance of the Printer class is created named myPrinter.
    • Two arrays are defined: intArray containing integers and stringArray containing strings.
    • The printArray method of myPrinter is called twice, once with intArray and once with stringArray.
    • After that, the program counts the number of methods named printArray declared in the Printer class using reflection.
    • If the count is greater than 1, it prints “Method overloading is not allowed!”.

Now let’s explain the approach:

  • The Printer class provides a generic method printArray that can print any type of array.
  • The Solution class demonstrates the usage of this generic method with both integer and string arrays.
  • The use of reflection to count the number of printArray methods serves as a check to ensure that only one method with this name exists in the Printer class, as overloading of this method is not allowed according to the problem constraints.

Overall, the solution demonstrates the usage of generics in Java, particularly for printing arrays of any type, and utilizes reflection to perform runtime checks on the defined methods.

Leave a Comment