Day 21: Generics | 30 Days Of Code | HackerRank Solution

Hello coders, today we are going to solve Day 21: Generics HackerRank Solution in C++, and Java.

Day 21: Generics

Objective

Today we’re discussing Generics; be aware that not all languages support this construct, so fewer languages are enabled for this challenge.

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 1 function named printArray.

Output Format

Your printArray function should print each element of its generic array parameter on a new line.

Solution – Day 21: Generics

C++

#include <iostream>
#include <vector>
#include <string>

using namespace std;

// Write your code here
template <class T> 
    void printArray(vector<T> i) 
 { 
    for(int j=0;j<i.size();j++) 
        cout<<i[j]<<endl;
 } 
int main() {
	int n;
	
	cin >> n;
	vector<int> int_vector(n);
	for (int i = 0; i < n; i++) {
		int value;
		cin >> value;
		int_vector[i] = value;
	}
	
	cin >> n;
	vector<string> string_vector(n);
	for (int i = 0; i < n; i++) {
		string value;
		cin >> value;
		string_vector[i] = value;
	}

	printArray<int>(int_vector);
	printArray<string>(string_vector);

	return 0;
}

Java

import java.util.*;

class Printer <T> {
        public static <E> void  printArray(E[] generic){
        for(E element: generic){
  System.out.println(element);
        }
    }
}
public class Generics {
    
    public static void main(String args[]){
        Scanner scanner = new Scanner(System.in);
        int n = scanner.nextInt();
        Integer[] intArray = new Integer[n];
        for (int i = 0; i < n; i++) {
            intArray[i] = scanner.nextInt();
        }

        n = scanner.nextInt();
        String[] stringArray = new String[n];
        for (int i = 0; i < n; i++) {
            stringArray[i] = scanner.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.");
        }
    } 
}

Disclaimer: The above Problem (Day 21: Generics) is generated by Hacker Rank but the Solution is Provided by CodingBroz. This tutorial is only for Educational and Learning Purpose.

Leave a Comment

Your email address will not be published. Required fields are marked *