[HackerRank] JAVA Generics

OOSEDUS·2025년 3월 10일
0

해커랭크

목록 보기
2/13
post-thumbnail

문제

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.


첫번째 시도: Compile Error

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로 선언해야함


두번째 시도 : Success

class Printer <T>
{
   public void printArray(T arr[]){
        for(T a:arr){
            System.out.println(a);
        }
   }
}

알아야할 개념

1. 제네릭(Generic)이란 ?
클래스, 메소드에서 사용할 데이터 타입을 나중에 확정하는 기법이다. 즉 인스턴스를 생성할 때 혹은 메소드를 호출할 때 타입을 확정할 수 있게 해주는 기법이다.
2. 제네릭 선언 방법은 ?
클래스에서 사용하려면 클래스 명 우측에 <>를 사용해서 선언한다.

profile
성장 가능성 만땅 개발블로그

0개의 댓글