250x250
jhs0129
프로그래밍
jhs0129
전체 방문자
오늘
어제
  • 분류 전체보기
    • 자격증
      • SQLD
      • 정보처리기사
    • 프로젝트
      • html csss js - todolist
      • JSP 방명록
      • 졸업작품
    • 공부기록
      • Java
      • Spring
      • Spring Security
      • Algorithm
      • JPA
      • DB
      • Servlet JSP
      • html
      • 기술공유
    • 잡다한 생각

블로그 메뉴

  • 홈
  • 태그
  • 방명록

공지사항

인기 글

태그

  • JPA
  • spring framework
  • 스프링 프레임워크
  • github
  • 스프링시큐리티
  • spring boot
  • oAuth2
  • cicd
  • spring data jpa
  • spring
  • EC2
  • nhn cloud 강의
  • 스프링
  • NHN Cloud
  • 프로젝트
  • AWS
  • Spring Security Login
  • codedeploy
  • Spring Security
  • rest docs

최근 댓글

최근 글

티스토리

반응형
hELLO · Designed By 정상우.
jhs0129

프로그래밍

공부기록/Java

제네릭(1)

2021. 8. 7. 18:49
320x100
반응형

제네릭을 사용하는 이유

  • 잘못된 타입이 사용될 수 있는 문제를 컴파일 과정에서 제거할 수 있음
  • 타입변환을 제거할 수 있음
List list = new ArrayList();
list.add("hello");
Strign str = (String) list.get(0);

//List에 저장되는 요소를 String타입으로 변환하지 않아도 된다.
List<String> list = new ArrayList<String>();
list.add("hello");
String str = list.get(0);
  • 하나의 메소드로 여러 타입을 다룰 수 있음
public class Box<T>{
	private T t;
    public T get() { return t; }
    public void set(T t) { this.t = t; }
}​

<T> 에서 T에 wrapper class로 변경해서 작성

기본형 wrapper class
boolean Boolean
char Character
byte Byte
short Short
int Integer
long Long
float Float
double Double
  • 파라미터를 두 개 이상 사용할수 있음, 객체로도 사용 가능

제네릭 메소드

리턴타입 앞에 <>기호를 추가하고 안에 타입 파라미터를 기술 매개변수의 타입을 타입 파라미터로 사용

  • [접근 제어자] <제네릭타입, ...> [반환타입] 메소드명 ([제네릭타입] 파라미터, ...)

ex)

제네릭 타입

public class Pair<K, V>{
	private K key;
    private V value;
    
    public Pair(K key, V value){
    	this.key = key;
        this.value = value;
    }
    
    public void setKey(K key) { this.key = key;}
    public void setValue(V value) { this.value = value;}
    public K getKey() { return key;}
    public V getValue() { return value;}
}

제네릭 메소드

public class Util{
	public static <K, V> boolean compare(Pair<K,V> p1, Pair<K, V> p2){
    	boolean keyCompare = p1.getKey.equals(p2.getKey());
        boolean valueCompare = p1.getValue.equals(p2.getValue());
        return keyCompare && valueCompare;
}

호출

public class ex{
	public static void main(String[] args){
    	Pair<Integer, String>p1 = new Pair<Integer, String>(1,"사과");
        Pair<Integer, String>p2 = new Pair<Integer, String>(1,"사과");
        boolean result = Util.<Integer, String>compare(p1, p2);
        
        if(result)
        	System.out.println("true");
        else
        	System.out.println("false");
}
320x100
반응형

'공부기록 > Java' 카테고리의 다른 글

람다  (0) 2022.04.16
제네릭(2)  (0) 2021.08.09
스레드(3)  (0) 2021.08.07
스레드(2) - Runnable(Interface) vs Thread (Class)  (0) 2021.08.03
스레드(1) - 생성  (0) 2021.08.03
    '공부기록/Java' 카테고리의 다른 글
    • 람다
    • 제네릭(2)
    • 스레드(3)
    • 스레드(2) - Runnable(Interface) vs Thread (Class)
    jhs0129
    jhs0129
    공부기록 남기기

    티스토리툴바