본문 바로가기

Algorithms/30 Days of Code

Day 21: Generics

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.


풀이

package Day21;

public class Printer <T>{

<T> void printArray(T[] array){
for(int i = 0; i < array.length; i++){
System.out.println(array[i]);
}
}
}


package Day21;

import java.util.Scanner;

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.");
}
}
}


'Algorithms > 30 Days of Code' 카테고리의 다른 글

Day 24: More Linked Lists  (0) 2018.03.09
Day 23: BST Level-Order Traversal  (0) 2018.03.08
Day 20: Sorting  (0) 2018.03.08
Day 19: Interfaces  (0) 2018.02.27
Day 18: Queues and Stacks  (0) 2018.02.27