Generic methods are a very efficient way to handle multiple datatypes using a single method. This problem will test your knowledge on Java Generic methods.
Let's say you have an integer array and a string array. You have to write a single method printArray that can print all the elements of both arrays. The method should be able to accept both integer arrays or string arrays.
You are given code in the editor. Complete the code so that it prints the following lines:
1
2
3
Hello
World
Do not use method overloading because your answer will not be accepted.
class Printer <T>
{
public void printArray(T arr[]){
for(a:arr){
System.out.println(a);
}
}
}
Compile time error
Solution.java:7: error: bad initializer for for-loop
for(a:arr){
^
1 error
문제 원인 : 배열 값을 순회하는 for문을 활용하려고 했으나, 앞에 type을 선언하지 않고 사용함
해결 방법 : a 앞에 type을 T로 선언해야함
class Printer <T>
{
public void printArray(T arr[]){
for(T a:arr){
System.out.println(a);
}
}
}
1. 제네릭(Generic)이란 ?
클래스, 메소드에서 사용할 데이터 타입을 나중에 확정하는 기법이다. 즉 인스턴스를 생성할 때 혹은 메소드를 호출할 때 타입을 확정할 수 있게 해주는 기법이다.
2. 제네릭 선언 방법은 ?
클래스에서 사용하려면 클래스 명 우측에 <>를 사용해서 선언한다.