Generic

jinkyung·2021년 1월 15일
0

JAVA2

목록 보기
25/35

들어가는 데이터 자료형을 우리가 정해주고 싶어서 Generic을 만들었다.

package ex05.generic.understand00;

/*
1970년대 이전 "소프트웨어의 위기" 
=> 극복 : 단위
                 이해하기 쉽게
                 재사용성
1971 : C - 절차지향적/구조적 프로그래밍
1980년대 : C++ - 객체지향 프로그래밍
       1) C with Class
       2) C++
       3) 객체지향 + 일반화 프로그래밍
1995 : Java - 객체지향 프로그래밍, 대중화
2001 : C# - 객체지향 프로그래밍, 대중화+특수성

<일반화 프로그래밍>
알렉산더 스테파노프 1979년에 창안 Ada->C++
비야네 : 추후 C++ 표준으로 포함
       Template(형판, 모양자)
       -> General Programming(Generic Programming)
       -> 일반화 프로그래밍
       
Java, C# : Generic
           Generic + 자료구조 = Collection Framework
*/
public class WrapperInt {
	private int num;
	
	public WrapperInt(int num){
		this.num = num;
	}

	@Override
	public String toString() {
		return ""+num;
	}

}
package ex05.generic.understand00;

/*
int만 쓰는게아니라 다양한 자료형을 담고 싶은데 .. 일일이 클래스를 만들고 tostring을 오버라이딩? no! 
저장 : 논리적인 일 
저장대상 : int, double, short, long, String 

*/

public class WrapperMain {
	public static void main(String[] args) {
		WrapperInt wInt = new WrapperInt(10);
		System.out.println(wInt);
	}
}

제네릭에는 object를 상속받은 대상만 들어갈 수 있음 --> int 대신 integer를 만듦.

package ex05.generic.understand01;

/*

java 컴파일러는 Generic에 대입되는 자료형이 반드시 Object를 상속받아야 하도록 하였다.
즉, Class 타입이어야 한다. 
그런데 primitive 타입은 기본 자료형이므로 해당되지 않는다. 
그래서 새롭게 primitive 타입에 대한 Wrapper class를 나중에 추가하였다.

*/
public class WrapperMain {
	public static void main(String[] args) {
		WrapperType<Integer> wInt = new WrapperType<Integer>(10);
		System.out.println(wInt);
		
		WrapperType<Double> wDouble = new WrapperType<Double>(3.14);
		System.out.println(wDouble);
		
		WrapperType<String> wString = new WrapperType<String>("대한민국");
		System.out.println(wString);
		
		WrapperType<Person> wPerson = new WrapperType<Person>(new Person("홍길동",24));
		System.out.println(wPerson);
	}
}
package ex05.generic.understand01;

//T에 대입된 자료형으로 T를 치환하겠다.
//T(template)는 지시대명사로 다른 글자가 와도 된다 

public class WrapperType<T> {
	private T num;
	
	public WrapperType(T num){
		this.num = num;
	}

	@Override
	public String toString() {
		return ""+num;
	}

}
package ex05.generic.understand01;

public class Person {
	private String name;
	private int age;
	
	public Person(String name, int age) {
		this.name = name;
		this.age = age;
	}

	@Override
	public String toString() {
		return name+":"+age;
	}	
}

List : 저장된 순서 유지

Hash : 저장은 list보다 느리지만 검색은 가장 빠름 .

T 라는 제네릭을 이용해서 linked list라는 자료구조를 만들었다. (컬렉션에 적용)

package ex05.generic.linkedlist02;

/*
<Generic의 가장 많이 쓰이는 용도>
1) 논리(처리)는 동일
2) 자료형이 다르다

=> 자료구조, 알고리즘
  Data Structure = Container = Collection
*/

class Element<T>{				//T타입의 자료들을 받겠다.
	public Element<T> next;		//다음 객체 위치 저장 
	public T item;				//데이터 
}

public class ElementMain {
	public static void main(String[] args) {
		Element<String> head = new Element<String>();
		Element<String> cur = null;			// 현재 저장위치 변수 
		cur = head;							// 최초 위치는 head 
		head.item = "1. 라이언킹";
		
		cur.next = new Element<String>();
		cur = cur.next;
		cur.item = "2. 타이타닉";
		
		cur.next = new Element<String>();
		cur = cur.next;
		cur.item = "3. 바람과 함께 사라지다";		
		
		cur.next = new Element<String>();
		cur = cur.next;
		cur.item = "4. 슬럼독 밀리어네어";
		
		showAll(head);
	}
	
	public static void showAll(Element<String> head) {
		Element<String> curr = head;
		while(curr != null) {
			System.out.println(curr.item);
			curr = curr.next;
		}
	}
}
package ex05.generic.linkedlist03;

/*
<Generic의 가장 많이 쓰이는 용도>
1) 논리(처리)는 동일
2) 자료형이 다르다

=> 자료구조, 알고리즘
  Data Structure = Container = Collection
*/

class Element<T>{
	public Element<T> next;		// 다음 객체 위치 저장
	public T item;				// 데이터
}

class Person{
	private String name;
	private int age;
	
	Person(String name, int age){
		this.name = name;
		this.age = age;
	}
	
	//오버라이딩 
	public String toString() {	
		return name+":"+"age";		
	}

}

public class ElementMain {
	public static void main(String[] args) {
		Element<Person> head = new Element<Person>();
		Element<Person> cur = null;	// 현재 저장 위치
		cur = head;					// 최초 위치는 head
		head.item = new Person("홍길동", 24);
		
		cur.next = new Element<Person>();
		cur = cur.next;
		cur.item = new Person("임꺽정", 33);
		
		cur.next = new Element<Person>();
		cur = cur.next;
		cur.item = new Person("장길산", 53);	
		
		cur.next = new Element<Person>();
		cur = cur.next;
		cur.item = new Person("일지매", 42);	
		
		showAll(head);
	}
	
	public static void showAll(Element<Person> head) {
		Element<Person> curr = head;
		while(curr != null) {
			System.out.println(curr.item);  //toString을 오버라이딩했으므로 값 출력.
			curr = curr.next;
		}
	}
}

0개의 댓글