삽질개발

[Mindev 개발공부]Java 지네릭스(Generics)에 대하여 알아보겠습니다. 본문

Java

[Mindev 개발공부]Java 지네릭스(Generics)에 대하여 알아보겠습니다.

MinDev 2017. 9. 7. 00:06

지네릭스(Generics)란 다양한 타입의 객체들을 다루는 메서드나 컬렉션 클래스에 컴파일 시의 타입체크를 해주는 기능입니다.


지네릭스를 쓰면 얻는효과는

1. 타입의 안정성

2.코드가 간결해진다.


간단한 예제를 보겠습니다.


예를 들어  예시된 Car 클래스가 있다고 가정해봅시다.


 public class Car {

Object speed;


void setspeed(Object speed) {

this.speed = speed;

}


Object getspeed() {

return speed;

}

}


이제 이클래스를 지네릭 클래스로 변경하게되면 클래스옆에 <T>를 붙이면 된다.


 public class Car<T> {

T speed;


void setSpeed(T speed) {

this.speed = speed;

}


T getSpeed() {

return speed;

}

}


여기서 <T> 의 T는 타입변수라곱하며 T대신 참조형 타입 String,Integer 등 지정해도 상관없다.




이제 배운걸 실제로 코드로 확인해보자

class Fruit {

public String toString() {

return "Fruit";

}

}


class Apple extends Fruit {

public String toString() {

return "Apple";

}

}


class Grape extends Fruit {

public String toString() {

return "Grape";

}

}


class Toy {

public String toString() {

return "Toy";

}

}


class FruitBoxEx1 {

public static void main(String[] args) {

Box<Fruit> fruitBox = new Box<Fruit>();

Box<Apple> appleBox = new Box<Apple>();

Box<Toy> toyBox = new Box();

// Box<Grape> grapeBox = new Box<Apple>(); //error 타입불이치


fruitBox.add(new Fruit());

fruitBox.add(new Apple());

appleBox.add(new Apple());

appleBox.add(new Apple());

// appleBox.add(new Toy()); //error Apple class와 관계 x

toyBox.add(new Toy());

// toyBox.add(new Apple()); //error Toy class와 관계 x

System.out.println(fruitBox);

System.out.println(appleBox);

System.out.println(toyBox);

}

}


class Box<T> {

ArrayList<T> list = new ArrayList<T>();


void add(T item) {

list.add(item);

}


T get(int i) {

return list.get(i);

}


int size() {

return list.size();

}


public String toString() {

return list.toString();

}

}


여기서 보시게되면 자신의 부모는 상관이없지만 자식은 호출할수없는걸 볼수가있습니다.

또한 지네릭 타입이 맞지않을경우 또한 error 가 발생합니다.

저 코드를 실행하게되면 


컴파일결과

[Fruit, Apple]

[Apple, Apple]

[Toy]


github : https://github.com/mkw8263


Comments