스터디사이트 : https://www.hackerrank.com



JAVA Basic : 제네릭



제네릭 원리를 이용하여 입력되는 배열을 한 줄에 한 원소씩 출력되게 코딩하라.


제네릭이란,

(제네릭 : 포괄적인, 일반적인)

클래스 내부에서 사용할 데이터 타입을 외부에서 지정하는 기법


제네릭의 쓰임1 - 클래스

class Person<T, S>{

    public T info;

    public S id;

    Person(T info, S id){ 

        this.info = info;

        this.id = id;

    }

}


제네릭의 쓰임2 - 메소드

public <U> void printInfo(U info){

        System.out.println(info);

}


제네릭 지정 <> 안에 클래스 문자 지정은 자유. 본래 <U extends Object> 의 생략형이라고 생각하면 된다.

※ 제네릭 메소드의 파라미터는 U 가 아니더라도 U[] 형의 데이터형도 정의 가능하다.



※ 주어진 코딩

지정한 영역에서만 코딩하시오


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
class Solution{
 
    * Write your code here *
 
    public static void main(String args[]){
        Integer[] intArray = { 123 };
        String[] stringArray = { "Hello""World" };
        
        printArray( intArray  );
        printArray( stringArray );
        
        if(Solution.class.getDeclaredMethods().length > 2){
            System.out.println("You should only have 1 method named printArray.");
        }
    } //end method main()
//end class Solution
cs


입력

{1, 2, 3};    {"Hello", "World"};

출력

1

2

3

Hello

World



추가설명

해당 문제는 메소드를 이용한 제네릭의 사용이다.

제네릭 메소드를 불러오는 곳의 메소드는 static이므로, 

호출되는 메소드도 static으로 지정해야 컴파일 에러가 뜨지 않는다.

제네릭 메소드 문법사용순서는 아래와 같이 하면 된다.


public static <E> void printArray(E[] e){

내용

}


그리고 static과 리턴타입(void) 사이에 집어넣은 제네릭 지정은 E이지만, 파라미터 정의란에 E[] 형태로 배열 정의도 가능하다.



결과

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
class Solution{
 
    public static <E> void printArray(E[] e){
        for(int i=0; i<e.length; i++){
            System.out.println(e[i]);
        }
    } //end method printArray
 
    public static void main(String args[]){
        Integer[] intArray = { 123 };
        String[] stringArray = { "Hello""World" };
        
        printArray( intArray  );
        printArray( stringArray );
        
        if(Solution.class.getDeclaredMethods().length > 2){
            System.out.println("You should only have 1 method named printArray.");
        }
    } //end method main()
//end class Solution
cs

결과 : 

1

2

3

Hello

World



+ Recent posts