Hello Programmers/Coders, Today we are going to share solutions of Programming problems of 30 Days Of Code, HackerRank. At Each Problem with Successful submission with all Test Cases Passed, you will get an score or marks. And after solving maximum problems, you will be getting stars. This will highlight your profile to the recruiters.
In this post, you will find the solution for Day 21: Generics in Java-HackerRank Problem. We are providing the correct and tested solutions of coding problems present on HackerRank. If you are not able to solve any problem, then you can take help from our Blog/website.
Use “Ctrl+F” To Find Any Questions Answer. & For Mobile User, You Just Need To Click On Three dots In Your Browser & You Will Get A “Find” Option There. Use These Option to Get Any Random Questions Answer.
Link for the Problem – Day 21: Generics – Hacker Rank Solution
Day 21: Generics – Hacker Rank Solution
Problem:
Objective
Today we’re discussing Generics; be aware that not all languages support this construct, so fewer languages are enabled for this challenge. Check out the Tutorial tab for learning materials and an instructional video!
Task
Write a single generic function named printArray; this function must take an array of generic elements as a parameter (the exception to this is C++, which takes a vector). The locked Solution class in your editor tests your function.
Note: You must use generics to solve this challenge. Do not write overloaded functions.
Input Format
The locked Solution class in your editor will pass different types of arrays to your printArray function.
Constraints
- You must have exactly function named printArray.
Output Format
Your printArray function should print each element of its generic array parameter on a new line.
Day 21: Generics – Hacker Rank Solution
import java.util.Scanner; /** * @author Techno-RJ * */ class Printer<T> { void printArray(T[] inputArray) { for (T t : inputArray) { System.out.println(t); } } } public class Day21Generics { public static void main(String args[]) { Scanner sc = new Scanner(System.in); int n = sc.nextInt(); Integer[] intArray = new Integer[n]; for (int i = 0; i < n; i++) { intArray[i] = sc.nextInt(); } n = sc.nextInt(); String[] stringArray = new String[n]; for (int i = 0; i < n; i++) { stringArray[i] = sc.next(); } Printer<Integer> intPrinter = new Printer<Integer>(); Printer<String> stringPrinter = new Printer<String>(); intPrinter.printArray(intArray); stringPrinter.printArray(stringArray); if (Printer.class.getDeclaredMethods().length > 1) { System.out.println("The Printer class should only have 1 method named printArray."); } sc.close(); } }