본문 바로가기
개발/Java

java - Generics & Wildcard

by Devsong26 2017. 12. 16.

1. Generics?

 

자바 컬렉션 프레임워크는 자료구조로써 여러 타입의 객체를 저장할 수 있다.

컬렉션은 여러 타입의 객체를 저장하기 위해 기본적으로 입력 타입을 최상위 부모 클래스인

Object 형태로 저장되고 관리되도록 설계되었다하지만 런타임 시에 컬렉션을 사용하는

메소드에서 의도한 객체를 다루는 로직을 수행 중에 의도되지 않는 객체가 나와 에러를

발생시킬 수 있다.

 

- Generics는 컬렉션의 입력되는 객체의 형안정성을 위해 사용되었다입력으로 정해진 객체

타입만을 받는다고 명시를 하는 것이다.

 

이로 인해 입력으로 받아들이면 안 되는 객체 타입을 입력 단계에서 걸러버린다.

 

 

* Generics 타입 매개변수

 

E: Element를 의미컬렉션의 요소 표시할 때 사용

 

T: Class Type을 의미

 

V: Value를 의미

 

K: Key를 의미

 

 

import java.util.Date;

public class GenericTest{
  public static void main(String[] args){
    ExampleGeneric<Date> example = new ExampleGeneric<Date>();
    Date testDate = new Date();
    example.setGenericProperty(testDate);
    System.out.println(example.getGenericProperty());
  }
}

class ExampleGeneric<T>{
  T genericProperty;

  public T getGenericProperty(){
  	return genericProperty;
  }

  public void setGenericProperty(T genericProperty){
  	this.genericProperty = genericProperty;
  }
}

 

 

2. Wildcard란?

Generics로 구현된 메소드의 경우 Generics타입만 매개변수로 입력을 해야 한다.

Generics를 상속받은 클래스 역시 Generics의 속성을 가지므로 입력이 가능할 것 같다. 

하지만 Generics는 형안정성을 중시하기 때문에 지정된 Generics 타입 이외의 타입은 입력으로 받지 않는다. 

Generics의 다형성을 허용하기 위해 사용되는 것이 와일드카드이다. 

 

* Wildcard의 종류

?는 알 수 없는 타입을 의미

 

<?> - 모든 객체 자료형, 내부적으로는 Object로 인식

<? Super 클래스> - 명시된 클래스와 그 상위 클래스

<? extends 클래스> - 명시된 클래스와 그 클래스를 상속받은 모든 클래스

 

 

 

#예시코드 시나리오

- 건물에 입장하기 위해 부모가 검사를 받고 통과했다.

- 이 건물은 부모만 통과하면 자식도 입장 허가를 받는다.

 

 

public class WildcardTest{

  public static void main(String[] args){
    Parent mother = new Parent("mother");
    Parent father = new Parent("father");
    Child syster = new Child("syster");
    Child me = new Child("me");
    LIst<Parent> parents = new ArrayList<Parent>();
    parents.add(mother);
    parents.add(father);
    entranceTest(parents);

    List<Child> children = new ArrayList<Child>();
    children.add(syster);
    children.add(me);
    entranceTest(children);
  }

  private static void entranceTest(List<? extends Parent> humanList){
    Iterator iter = humanList.iterator();
    while(iter.hasNext()){
      Parent man = (Parent)iter.next();
      System.out.println(man.identity+" is enable entrance");
    }
  }
  
}

class Parent{

  String identity;

  protected Parent(String identity){
  	this.identity = identity;
  }
  
}



class Child extends Parent{

  protected Child(String identity){
  	super(identity);
  }
  
}   

 

 


더 많은 내용을 보시려면 아래를 참고하세요.


블로그의 다른 글

 

Apache POI

아파치 POI는 서버에 엑셀파일을 업로드하기 위해 사용해봤다. 위키백과의 설명에 따르면 아래와 같다. 아파치 POI(Apache POI)는 아파치 소프트웨어 재단에서 만든 라이브러리로서 마이크로소프

developer-syubrofo.tistory.com

 

JUnit

JUnit이란? TDD 방법론에 의해 자바에서 테스트 코드를 작성할 때 사용하는 서바 사이드 테스트 도구이다. JUnit은 단정문(테스트의 성공과 실패를 판별하는 문장)인 assert 메소드를 이용하여 테스트

developer-syubrofo.tistory.com

 

Spring으로 다국어 페이지 만들기

회사 홈페이지를 다국어로 퍼블리싱을 해야 한다는 이야기를 듣고 나서 Spring을 이용한 다국어 페이지 만드는 방법을 여러가지 검색을 해보면서 구현을 해봤다. 나는 메세지 번들까지는 사용하

developer-syubrofo.tistory.com

 

Spring Lombok

이번에 새롭게 투입된 프로젝트에서는 lombok이라는 라이브러리를 사용하고 있다. 처음에는 이것의 존재를 모르고 있었는데, Github에서 프로젝트를 Cloning하고 Maven 업데이트를 했는데 프로젝트에

developer-syubrofo.tistory.com

 

[Java] Service, Controller 테스트

Junit으로 TDD를 실천하면서 어떻게 코드를 테스트 해야하는지 감이 잡혀온다. 알게 된 점은 아래와 같다. 1. 테스트 코드 작성법 2. 고민되는 부분 3. MockMvc의 사용법 4. Assert 사용법 1. 테스트 코드

developer-syubrofo.tistory.com

 

'개발 > Java' 카테고리의 다른 글

Spring Lombok  (0) 2018.04.26
Apache POI  (0) 2018.01.24
lang package - String 사용하는 방법  (0) 2017.11.19
List - LinkedList 사용하는 방법  (0) 2017.11.18
Set - LinkedHashSet 사용하는 방법  (0) 2017.11.17