HackerRank Solution for Java Generics
Problem description :-
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:
Solution :-
import java.lang.reflect.Method;
class Printer {
<T> void printArray(T[] array) {
for (T value : array) {
System.out.println(value);
}
}
}
public class JavaGenerics {
public static void main( String args[] ) {
Printer myPrinter = new Printer();
Integer[] intArray = { 1, 2, 3 };
String[] stringArray = {"Hello", "World"};
myPrinter.printArray(intArray);
myPrinter.printArray(stringArray);
int count = 0;
for (Method method : Printer.class.getDeclaredMethods()) {
String name = method.getName();
if(name.equals("printArray"))
count++;
}
if(count > 1)System.out.println("Method overloading is not allowed!");
}
}
Output :-
1
2
3
Hello
World
Explanation :-
- In Java, T stands for Type in Generics. So we can pass any type of Object parameter. like String, Integer, Float, Double.
- We loop through array of T and print values one by one using println method.
We can also use Object instead of Generic in this solution but it is not valid solution because it does not satisfy Problem description. Let's see how we can done using Object.
import java.lang.reflect.Method;
class Printer {
public void printArray(Object[] array) {
for (Object value : array) {
System.out.println(value);
}
}
}
public class JavaGenerics {
public static void main( String args[] ) {
Printer myPrinter = new Printer();
Integer[] intArray = { 1, 2, 3 };
String[] stringArray = {"Hello", "World"};
Float[] floatArray = { 1.1F, 2.2F };
myPrinter.printArray(intArray);
myPrinter.printArray(stringArray);
myPrinter.printArray(floatArray);
int count = 0;
for (Method method : Printer.class.getDeclaredMethods()) {
String name = method.getName();
if(name.equals("printArray"))
count++;
}
if(count > 1)System.out.println("Method overloading is not allowed!");
}
}
Other HackerRank solutions in Java with Explanation :-
Comments
Post a Comment