Java Day 21: Generics




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.



  1. import java.util.*;
  2. class Printer <T> {
  3. /**
  4. * Method Name: printArray
  5. * Print each element of the generic array on a new line. Do not return anything.
  6. * @param A generic array
  7. **/
  8. // Write your code here
  9. public static <E> void printArray(E[] generic){
  10. for(E element : generic) {
  11. System.out.println(element);
  12. }
  13. }
  14. }
  15. public class Generics {
  16. public static void main(String args[]){
  17. Scanner scanner = new Scanner(System.in);
  18. int n = scanner.nextInt();
  19. Integer[] intArray = new Integer[n];
  20. for (int i = 0; i < n; i++) {
  21. intArray[i] = scanner.nextInt();
  22. }
  23. n = scanner.nextInt();
  24. String[] stringArray = new String[n];
  25. for (int i = 0; i < n; i++) {
  26. stringArray[i] = scanner.next();
  27. }
  28. Printer<Integer> intPrinter = new Printer<Integer>();
  29. Printer<String> stringPrinter = new Printer<String>();
  30. intPrinter.printArray( intArray );
  31. stringPrinter.printArray( stringArray );
  32. if(Printer.class.getDeclaredMethods().length > 1){
  33. System.out.println("The Printer class should only have 1 method named printArray.");
  34. }
  35. }
  36. }
Please click on the like button if it worked

Solution not working or have any suggestions? Please send an email to [email protected]


donate a cup of tea :)


Join Our Facebook Group

Share this solution


download android app

Popular HackerRank Java Solutions








codesadda.com

Codesadda.com is your home of programming solutions, tutorials, video tutorials and much more. Sign Up for our weekly newsletter to get update about new content.

Like us on Facebook | Connect with us on LinkedIn | Subscribe our Channel on Youtube