ABOUT ME

-

Today
-
Yesterday
-
Total
-
  • [11회차-②] JAVA (제네릭-①)
    JAVA 2021. 4. 6. 20:59

    강의명 : 오픈프레임워크 활용 디지털융합 SW엔지니어 양성 과정

    강의 날짜 : 21.04.06

     

    <제네릭>

     

    제네릭 프로그래밍(generic)이란 다양한 종류의 데이터를 처리할 수 있는 클래스와 메소드를 작성하는 기법이다.

     

    1. 제네릭 클래스

     

    자료형을 T라고 적어 모든 것을 수용하게 하여 객체를 생성할 때 자료형을 선언할 수 있게 한다.

    대표적인게 ArrayList 배열이다.

     

    예제 1.

    public class SimplePair<T> { //<T>로 제네릭 클래스임을 표시
    	
    	private T data1; //자료형이 선언되지 않은 변수 data1
    	private T data2; //자료형이 선언되지 않은 변수 data2
    	
    	public SimplePair(T data1, T data2) { //자료형이 선언되지 않은 인수를 받은 생성자
    		this.data1=data1;
    		this.data2=data2;
    	}
    	
    	public T getFirst() {
    		return data1;
    	}
        
    	public T getSecond() {
    		return data2;
    	}
    	
    	public void setFirst(T data1) { 
    		this.data1=data1;
    	}
        
    	public void setSecond(T data2) {
    		this.data2=data2;
    	}
    }
    public class SimplePairTest {
    
    	public static void main(String[] args) {
    		
    		SimplePair<String> pair=new SimplePair<String>("apple","tomato"); 
    		//객체를 생성할 때 String으로 자료형 선언
    		System.out.println(pair.getFirst());
    		System.out.println(pair.getSecond());
    	}
    }

     

    예제 2.

    public abstract class Material { //추상클래스 
    	public abstract void doPrinting();
    }
    public class Powder extends Material { //추상 클래스 상속
    	
    	public void doPrinting() {
    		System.out.println("Powder 재료로 출력함니다.");
    	}
        
    	public String toString() {
    		return "재료는 Powder입니다";
    	}
    }
    public class Plastic extends Material{ //추상 클래스 상속
    
    	public void doPrinting() {
    		System.out.println("Plastic 재료로 출력합니다.");
    	}
        
    	public String toString() {
    		return "재료는 Plastic 입니다.";
    	}
    }
    public class GenericPrinter<T> { //제네릭 클래스
    	private T material; //자료형이 선언되지 않은 변수 material
    	
    	public void setMaterial(T material) {
    		this.material=material;
    	}
        
    	public T getMaterial() {
    		return material;
    	}
    	
    	public String toString() {
    		return material.toString();
    	}
    }
    public class GenericPrinterTest {
    
    	public static void main(String[] args) {
    		//제네릭 클래스가 Powder형식을 받아오는 형식을 받는 powderPrinter
    		GenericPrinter<Powder> powderPrinter = new GenericPrinter<Powder>();
            
    		//Powder 클래스를 가져와서 Power형인 material에 저장
    		powderPrinter.setMaterial(new Powder()); 
    		//Powder형인 powder에 material을 저장
    		Powder powder = powderPrinter.getMaterial();
    		//String toString함수를 호출하게 되는데 자료형이 Powder이므로 자식 클래스 Powder가 실행
    		System.out.println(powderPrinter);
    		
    		//Power의 경우가 다 Plastic인 경우
    		GenericPrinter<Plastic> plasticPrinter = new GenericPrinter<Plastic>();
    		plasticPrinter.setMaterial(new Plastic());
    		Plastic plastic = plasticPrinter.getMaterial();
    		System.out.println(plasticPrinter);
    	}
    }

     

     

    예제 3.

    public class OrderdPair<K,V> { //자료형이 여러 개인데 선언되지 않은 제네릭 클래스
    	private K key;
    	private V value;
    	
    	public OrderdPair(K key,V value) {
    		this.key=key;
    		this.value=value;
    	}
        
    	public K getKey() {
    		return key;
    	}
        
    	public V getValue() {
    		return value;
    	}
    }

     

    public class OrderedPairTest {
    
    	public static void main(String[] args) {
    		//문자열,정수형으로 자료형 선언하면서 객체 생성
    		OrderdPair<String,Integer> p1=new OrderdPair<String,Integer>("mykey ",12345678);
    		//문자열,문자열로 자료형 선언하면서 객체 생성        
    		OrderdPair<String,String> p2=new OrderdPair<String,String>("java"," a programming language");
    		
    		System.out.println(p1.getKey()+""+p1.getValue());
    		System.out.println(p2.getKey()+""+p2.getValue());
    	}
    }

     

     

    2. 제네릭 메소드

     

    일반 클래스의 메소드에서도 타입 매개 변수를 사용하여 제네릭 메소드를 정의할 수 있다. 

    다만 타입 매개변수의 범위가 메소드 내부로 제한된다

     

    예제 1.

    public class MyArrayalg {
    	public static <T> T getLast(T[] a) { //메소드 앞에 <T>를 써주면서 제네릭메소드임을 알려줌
    		return a[a.length-1]; // 배열의 마지막 원소 출력
    	}
    }
    public class MyArray {
    	public static <T> void swap(T[] a,int i,int j) { //원소의 위치를 바꾸는 메소드
    		T tmp=a[i];
    		a[i]=a[j];
    		a[j]=tmp;
    	}
    }
    public class MyArrayTest {
    
    	public static void main(String[] args) {
    	
    		String[] language ={"C++","C#","JAVA"}; //배열 초기화
            
    		String last = MyArrayalg.getLast(language); //배열의 마지막 원소 반환
    		System.out.println(last);
            
    		MyArray.swap(language, 1, 2); //1번 인덱스 원소와 2번 인덱스 원소 교환
    		for(String value : language) //반복문으로 배열 출력
    			System.out.println(value);
    	}
    }

     

    예제 2.

    public class Point<T,V> { //제네릭 클래스
    	T x;
    	V y;
    	
    	Point(T x,V y){
    		this.x=x;
    		this.y=y;
    	}
    	
    	public T getX() {
    		return x;
    	}
    	
    	public V getY() {
    		return y;
    	}
    }
    public class GenericMethod {
    
    	
    	public static <T,V> double makeRectangle(Point<T,V> p1,Point<T,V> p2) {
        
    		double left =((Number)p1.getX()).doubleValue(); //실수로 받기 위한 메소드
    		double right =((Number)p2.getX()).doubleValue();
    		double top =((Number)p1.getY()).doubleValue();
    		double bottom =((Number)p2.getY()).doubleValue();
    		
    		double width =right-left;
    		double height=bottom-top;
    		
    		return width*height;
    	}
        
    	public static void main(String[] args) {
    		
    		Point<Integer,Double> p1 = new Point<Integer,Double>(0,0.0);
    		Point<Integer,Double> p2 = new Point<>(10,10.0); //생략 가능
    		
    		double rect=GenericMethod.<Integer,Double>makeRectangle(p1, p2);//<>생략 가능
    		System.out.println("두 점으로 만들어진 사각형의 넓이는 "+rect+"입니다.");
    	}
    }

     

    에제 3.

    public class genericMethodTest {
    
    	public static void main(String[] args) {
    		
    		Integer iArray[]= {10,20,30,40,50}; //정수형 배열
    		Double dArray[]= {1.1,1.2,1.3,1.4,1.5}; //실수형 배열
    		Character cArray[]= {'K','O','R','E','A'}; //문자형 배열
    		
    		printArray(iArray);
    		printArray(dArray);
    		printArray(cArray);
    	}
    	
    	public static <T> void printArray(T[] array) {
    		for(T element : array) {
    			System.out.printf("%s ",element); //자바에서는 %s가 모든 자료형이 받아짐
    		}
    		System.out.println();
    	}
    }

    'JAVA' 카테고리의 다른 글

    [12회차-②] JAVA (컬렉션 List 인터페이스)  (0) 2021.04.08
    [12회차-①] JAVA (제네릭-②)  (0) 2021.04.08
    [11회차-①] JAVA (스윙 컴포넌트)  (0) 2021.04.06
    [10회차] JAVA (그래픽)  (0) 2021.04.06
    [9회차-②] JAVA (이벤트)  (0) 2021.04.02
Designed by Tistory.