Problem : Write a Hacker Rank Solution For Day 21 : Generics or Hacker Rank Solution Program In Python and java For ” Day 21: Scope ” or Hacker Rank 30 days of code in Python and Java Solution: Day 21: Generics or Hackerrank solution for 30 Days of Code Challenges or Hacker rank 30 days of code in Python and Java Solution, Day 21: Generics , or Python and java Logic & Problem Solving: Day 21:Generics
Question :
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.
Solution :
HackerRank Day 21 : Java / python Solution 30 days of code : Generics
static <E> void printArray( E[] inputArray)
{
for( E e : inputArray)
{
System.out.println(""+e);
}
}
Solution in java 7
from typing import TypeVar
Element = TypeVar("Element")
def printArray(array: [Element]):
for element in array:
print(element)
vInt = [1, 2, 3]
vString = ["Hello", "World"]
printArray(vInt)
printArray(vString)
Solution in Python
using System;
class Solution
{
static void printArray<Element>(Element[] array)
{
foreach (var element in array)
{
Console.WriteLine(element);
}
}
static void Main(String[] args)
{
var vInt = new int[] { 1, 2, 3 };
var vString = new string[] { "Hello", "World" };
printArray<int>(vInt);
printArray<string>(vString);
}
}
Solution in C sharp
