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.
How I solved the problem
# generic으로 타입을 정의하지 않아도 재사용을 더 쉽게 할 수 있도록 함.
# printArray method의 paramter type을 Object[] 로 받으면 여러 타입을 받을 수 있음!
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 | import java.util.*; class Printer <T> { /** * Method Name: printArray * Print each element of the generic array on a new line. Do not return anything. * @param A generic array **/ // Write your code here public void printArray(Object[] genericArray){ for (Object object : genericArray) { System.out.println(object); } } } 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."); } } } | cs |
[출처 : https://www.hackerrank.com ]
'1 Day 1 Algorithms' 카테고리의 다른 글
[2019.01.14] BST Level-Order Traversal (0) | 2019.01.14 |
---|---|
[2019.01.11] Binary Search Trees (0) | 2019.01.11 |
[2019.01.09] Sorting (0) | 2019.01.09 |
[2019.01.08] Interfaces (0) | 2019.01.08 |
[2019.01.07] Queues and Stacks (0) | 2019.01.07 |
댓글