멀티캠퍼스 백엔드 과정 18일차[6월 27일] - java.base 모듈

GoldenDusk·2023년 7월 3일
0

제너릭

제너릭이란?

제네릭

  • 결정되지 않은 타입을 파라미터로 처리하고 실제 사용할 때 파라미터를 구체적인 타입으로 대체시키는 기능
  • 는 T가 타입 파라미터로 타입이 필요한 자리에 T를 사용할 수 있음

예제

class Box<T>{ //T는 타입 => 확장성이 좋아짐, String도 사용 가능하지만 그럼 확장성이 떨어짐
	//내가 담고 싶은 객체만 넣기 위해 제너릭을 사용
	public T content;
} // 박스를 하나 만듦

class Student{}

public class GenericEx
{

	public static void main(String[] args)
	{
		// Box 클래스를 이용하여 box 1개 생성
		//Box box1 = new Box();
		Box<String> box1 = new Box<String>(); //스트링 객체
		box1.content="안녕하세요"; //박스안에 안녕하세요라는 스트링 값이 들어감
		String str = box1.content;
		System.out.println(str); 
		box1.content = String.valueOf(1); // 정수 1을 문자열 "1"로 변환하는 메소드
		
		Box<Integer> box2 = new Box<>();
		box2.content = Integer.valueOf(3);
		
		box2.content =Integer.valueOf("2");
		
		Box<Student> stu = new Box<>(); //학생 객체만 넣기
		stu.content = new Student();
		stu.content = new Student();
		
	}

}

예제2

public class Box1<T>
{
	public T content; //현재 T의 객체타입은 object 타입이다.
	
	//Box의 내용물이 같은지 비교
	public boolean compare(Box1<T> other) { //box안의 내용물 검수
		boolean result = content.equals(other.content);
		return result;
	}
	
	public static void main(String[] args) {
		Box1 box1 = new Box1();
		box1.content="100";
		box1.content="100";
		box1.content="100";
		
		Box1 box2 = new Box1();
		box2.content ="100";
		
		Box1 box3 = new Box1();
		box3.content ="200";
		
		boolean result1 = box1.compare(box2); //내용물 비교
		System.out.println(result1); //true
		
		boolean result2 = box1.compare(box3); //내용물 비교
		System.out.println(result2); //false
	}
	
}

예제 3

class Product<K,M>{  //타입 파라미터를 K(kind)와 M(model)으로 정의 
	private K kind;
	private M model;     //타입파라미터를 필드 타입으로 정의 
	/**
	 * @return the kind
	 */
	public K getKind()
	{
		return kind;
	}
	/**
	 * @param kind the kind to set
	 */
	public void setKind(K kind)
	{
		this.kind = kind;
	}
	/**
	 * @return the model
	 */
	public M getModel()
	{
		return model;
	}
	/**
	 * @param model the model to set
	 */
	public void setModel(M model)
	{
		this.model = model;
	}
	
	
}      

class Tv{
	
}

class Car{
	public void run() {
		System.out.println("자동차가 달립니다.");
	}
}

class Home{
	
	public void turnOnLight() {
		System.out.println("전등불을 켰습니다.");
	}
}

class HomeAgency implements Rentable<Home>{

	@Override
	public Home rent()
	{
		// TODO Auto-generated method stub
		return new Home();
	}
	
}

class Radio{}

public class ProductGenericEx 
{

	public static void main(String[] args)
	{
		//Product 클래스에 K는 Tv로 Model은 String 으로 대체하여 p1제품을 생성하세요!
		Product<Tv,String> p1 = new Product<>();
		
		p1.setKind(new Tv());
		p1.setModel("스마트삼성파브");
		 Tv tv = p1.getKind();
		 System.out.println(tv.toString());
         System.out.println(p1.getModel());
   
         
       //Product 클래스에 K는 Car로 Model은 String 으로 대체하여 p2제품을 생성하세요!
       //p2를 이용하여 자동차(Car)를 생성하고 모델명은 "SUV-NEW카니발" 로 생성하세요
         
       Product<Car,String> p2 = new Product();
       
       p2.setKind(new Car());
       p2.setModel("SUV-NEW카니발");

       ShopManger carrent = new ShopManger();
       Car car = carrent.rent();
       car.run();
       
       HomeAgency homerent = new HomeAgency();
       Home home = homerent.rent();
       home.turnOnLight();
       
       
	}
public interface Rentable<P>
{
        P rent();   //다양한 대상을 렌트하기 위해 rent()메소드의 리턴 타입을 타입파라미터로 선언
}
public class ShopManger implements Rentable
{
	@Override
	public Car rent()
	{
		return null;
	}
	
}

예제 4 멀고등학교 안에 학생들만 받는 제너릭(그 구조만 받을 수 있음)

  class Student1<K, V>{
	private K key;
	private V value;
	
	public void set(K key, V value) {
		this.key = key;
		this.value=value;
	}

	public K getAge(int i)
	{
		return key;
	}

	public V getName(String name)
	{
		return value;
	}

}

class Container1<K, V>
{
	private K key;
	private V value;
	
	public void set(K key, V value) {
		this.key = key;
		this.value=value;
	}

	public K getKey()
	{
		return key;
	}

	public V getValue()
	{
		return value;
	}
	
	public static void main(String[] args) {
		Container1<String, String> contain = new Container1<String, String>();
		contain.set("홍길동", "도적");
		String name1 = contain.getKey();
		String job = contain.getValue();
		
		Container1<String, Student1> contain2 = new Container1<String, Student1>();
		contain2.set("멀티고등학교", new Student1());
		Student1 stu1 = contain2.getValue();
		stu1.getAge(20);
		stu1.getName("김진수");
		
		
	}
	
}

퀴즈

1. 제네릭에 대한 설명으로 틀린 것은?

  • 컴파일 시 강한 타입 체크 할 수 있다.
  • 타입 변환(casting)을 제거한다.
  • 제너릭 타입은 타입 파라미터를 가지는 제네릭 클래스와 인터페이스르 말한다.
  • 제네릭 메소드는 리턴 타입으로 타입 파라미터를 가질 수 없다.

2. ContainerExample 클래스의 main()메소드는 Containner 제네릭 타입을 사용하고 있습니다. main() 메소드에서 사용하는 방법을 참고해서 Container 제네릭 타입 선언해보세요.
<코드>

class Container<T> {
    private T content;
    public T getContent() {
        return content;
    }
    public void setContent(T content) {
        this.content = content;
    }
}
public class ContainerExample {
    public static void main(String[] args) {
        Container<String> container1 = new Container<String>();
        container1.setContent("홍길동");
        String str = container1.getContent();        
        Container<Integer> container2 = new Container<Integer>();
        container2.setContent(6);
        Integer value = container2.getContent();
    }
}

3. ContainnerExample 클래스의 main() 메소드는 Containner 제네릭 타입을 사용하고 있습니다. main()메소드에서 사용하는 방법 참고해서 Container 제네릭 타입 선언

public class Container1<K, V>
{
	private K key;
	private V value;
	public void set(K key, V value) {
		this.key = key;
		this.value=value;
	}
	public K getKey()
	{
		return key;
	}
	public V getValue()
	{
		return value;
	}	
	public static void main(String[] args) {
		Container1<String, String> contain = new Container1<String, String>();
		contain.set("홍길동", "도적");
		String name1 = contain.getKey();
		String job = contain.getValue();		
		Container1<String, Integer> contain2 = new Container1<String, Integer>();
		contain2.set("홍길동", 23);
		String name2 = contain.getKey();
		String age = contain.getValue();		
	}
	}

4. 다음 Util 클래스의 정적 getValue() 메소드는 첫 번째 매개값으로 Pair 타입과 하위 타입만 받고, 두 번째 매개값으로 키 값을 받습니다.
리턴값은 키값이 일치할 경우 Pair에 저장된 값을 리턴하고, 일치하지 않으면 null을 리턴하도록 Util 클래스와 getValue() 제네릭 메소드 작성

생각과 구조
Util 클래스를 만들되,
getValue() 메소드는 정적이고 1번째 매개값으로 Pair 타입과 하위 타입만 받고, 두 번째 매개값으로 키 값
=> 정적으로 해두는 이유가 Util은 Pair를 상속 안하기 때문
리턴 값은 if로 제한을 둬야 겠네...?

Pair.class
public class Pair<K, V>
{
	private K key;
	private V value;

	public Pair() {}
	public Pair(K key, V value) {
		this.key = key;
		this.value=value;
	}	
	/*
	 * public void set(K key, V value) { //값을 바꾸고 싶다면... set을 꼭 만들어줘라
	 * if(key.equals(key)) { this.value=value; } else
	 * System.out.println("값이 없습니다."); }
	 */

	public K getKey()
	{
		return key;
	}

	public V getValue()
	{
		return value;
	}
	
	
	
}

ChildPair,class

public class childPair<K, V> extends Pair<K, V>
{
	public childPair() {};
	public childPair(K k, V v) {
		super(k, v);
	}

	public static void main(String[] args) {
		Pair<String, Integer> p1 = new Pair("홍길동", 20);
		Integer age = Util.getValue(p1, "홍길동"); //이게 맞다면... 홍길동의 나이를 돌려줘라
		System.out.println(age);

		childPair<String, String> p2 = new childPair("멀티잇중학교", "경기도");
		String v = Util.getValue(p2, "멀티잇중학교");
		System.out.println(v);
			
	}

}

Util.class

public class Util
{
	public static <K, V>V getValue(Pair<K, V>p, K k){
		if(p.getKey()==k) {
			return p.getValue();
		}
		else return null;
	}
}

회고

월요일에 좀 쉬고 나갔다 왔더니 강의 듣는데 더 죽을 맛이다. 그래도 뭔가 매일 들으니 발전된 느낌? 오늘은 정보처리기사 실기도 신청했다 집 근처에 가까운 곳 있어서 신청 완료! 이번에는 제발 1개 차이로 떨어질 일 없길 ㅠㅠㅠㅠ

profile
내 지식을 기록하여, 다른 사람들과 공유하여 함께 발전하는 사람이 되고 싶다. 참고로 워드프레스는 아직 수정중

0개의 댓글