[JAVA] GENERIC

펭귄안녕·2024년 10월 18일

JAVA

목록 보기
1/9
post-thumbnail

자바 제네릭

제네릭 문법이 적용된 무엇이든 저장하고 리턴할 수 있는 박스

제네릭 등장 이전의 코딩 방식과 문제점

// 어떤 데이터든 넣고 뺄 수 있는 상자
public class BeforeBox {
    private Object obj;

    // 어떤 데이터든 저장할 수 있는 메서드
    public void setData(Object a){
        this.obj=a;
    }

    // 어떤 데이터든 뺄 수 있는 메서드
    public Object getData(){
        return obj;
    }

좋은 코딩은 컴파일 오류가 많이 나는 코드다.
컴파일 예외 : 코드를 실행하기 전에 발생하는 오류 > 빨간줄로 표시됨
런타임 예외 : 코드를 실행하면 발생하는 오류 > 빨간줄 표시X , 찾기 어려움

제네릭을 사용하지 않았을 때 단점

  1. 데이터를 리턴받을 때 매번 형변환 작업 진행
  2. 개발자의 실수로 발생하는 런타임 오류를 작성할 확률이 높다
public class BeforeBoxTest {

    public static void main(String[] args) {
        // BeforeBox 객체
        BeforeBox box1=new BeforeBox();
        box1.setData("apple");

        BeforeBox box2=new BeforeBox();
        box2.setData(5);

        BeforeBox box3=new BeforeBox();
        box3.setData(new Apple());

        BeforeBox box4=new BeforeBox();
        box4.setData(new Orange());

        //box1에 저장된 데이터를 받아오기
        String data1=(String)box1.getData();
        String data2=box1.getData().toString();

        int data3 = (int)box2.getData();

        Apple data4=(Apple) box3.getData();

        Orange data5=(Orange) box4.getData();

제네릭

T : 정해지지 않은 자료형
Box< T> : T가 자료형이 아니라 자료형이 정해지지 않은 제네릭 문법임을 컴파일러에게 인지

public class Box<T> {
    private T obj;


    // 어떤 데이터든 저장할 수 있는 메서드
    public void setData(T a){
        this.obj=a;
    }

    // 어떤 데이터든 뺄 수 있는 메서드
    public T getData(){
        return obj;
    }
}

class MemberVO{
    private String id;

    public void setId(String id){
        this.id=id;
    }
    public void getId(String id){
        this.id=id;
    }
}
public class BoxTest {

    public static void main(String[] args) {
        // 제네릭 문법이 적용된 클래스는 클래스 구현 시에는 자료형을 지정하지 않았다.
        // 제네릭 문법이 적용된 클래스의 자료형은 객체 생성 시 결정해야함.
        // Box 객체 생성
        Box<String> box1=new Box<>();
        box1.setData("java");
        String data1 = box1.getData();

        Box<Integer> box2=new Box<>();
        box2.setData(123);
        int data2 = box2.getData();

        // Apple 객체를 저장할 수 있는 박스
        Box<Apple> box3 = new Box<>();
        box3.setData(new Apple());
        Apple data3=box3.getData();

        Map<String,Integer> map = new HashMap<>();

        //MemberVO를 저장할 수 있는 box생성
        Box<MemberVO> box4=new Box<>();



    }
}

보편적인 제네릭 타입 선언 시 사용하는 문자

T - Type
E - Element
K - Key
V - Value
N - number

0개의 댓글