YJ의 새벽

JAVA (제네릭) 본문

SelfStudy/JAVA

JAVA (제네릭)

YJDawn 2023. 2. 4. 00:37

 

 

  • 제네릭스란??

 

-- 컴파일시 타입을 체크해주는 기능.

-- 객체의 타입 안정성을 높이고 , 형변환의 번거로움을 줄여줌.

-- 실행중 에러를 컴파일에러로 가져올수있게 해준다.

 

 

 

import java.util.*;

public class Example {
	public static void main(String[] args) {
	//	ArrayList list = new ArrayList();
		ArrayList<Integer> list = new ArrayList<Integer>();
		
		list.add(10);
		list.add(20);
		list.add("30");       // <Integer> 제네릭을 사용하면 오류발생. 
                               // 컴파일에러를 잡아준다.  (타입체크가 강화됨)
		
		int i = (int)list.get(2);   
		
		System.out.println(i);				
	}
}

 

 

 

  • 타입변수

-- 클래스 작성할 때 , Object 타입 대신 타입변수(E) 를 선언하여 사용.

  -- 일반클래스 --> 제네릭클래스.

import java.util.*;

class Tv {} 
class Audio{}
public class Example {
	public static void main(String[] args) {
 
		ArrayList<Tv> list = new ArrayList<Tv>(); //Tv타입 객체만 저장가능.
		
		list.add(new Tv());
		list.add(new Audio());  // Audio객체 에러발생.
		
		Tv tv = list.get(0);	
	}
}

 

 

 

*** 참조변수와 생성자의 대입된 타입은 일치해야한다. 

 

Product()의 자식클래스 Tv, Audio

 

 

 

 

    EX ))) 제네릭 예제  ( ArrayList )

 

import java.util.*;
class Student{
	String name;
	int ban;
	int no;
	
	public Student(String name, int ban, int no) {
		this.name =name;
		this.ban = ban;
		this.no = no;
	}
}
public class Example {
	public static void main(String[] args) {

		ArrayList<Student> list = new ArrayList<Student>();
		list.add(new Student("자바좀",1,1));
		list.add(new Student("그만",1,2)	);
		list.add(new Student("하고싶어요",2,1));
		
		Iterator<Student> it = list.iterator();
     //   Iterator it = list.iterator();
		while(it.hasNext()) {
		//	Student s = (Student)it.next();     --제네릭 사용하지않으면 형변환필요.
		//	Student s = it.next();        --이거
		//	System.out.println(s.name);   --두줄이랑             
            System.out.println(it.next().name);   --이거한줄 결과가 같음
		}		
	}
}

 

 

    EX ))) 제네릭 예제  HashMap < K,V >

--여러개의 타입변수가 필요한 경우 , 구분자 선언.

-- K : key        V : Value 

 

import java.util.*;
class Student{
	String name;
	int ban;
	int no;
	int kor;
	int eng;
	int math;
	
	public Student(String name,int ban,int no,int kor,int eng,int math) {
		this.name =name;
		this.ban = ban;
		this.no = no;
		this.kor = kor;
		this.eng = eng;
		this.math = math;
	}
}
public class Example {
	public static void main(String[] args) {

		HashMap<String,Student> map = new HashMap<>();
		map.put("자바좀",new Student("자바좀",1,1,100,100,100));
		
		Student s = map.get("자바좀");    -- 키로
		System.out.println(s.name);      -- 값을 가져온다
		}		
	}

 

 

  • 제한된 제네릭 클래스

--extends로 대입할 수 있는 타입을 제한.

 

 

    EX )))) 예제 .

 

import java.util.*;

interface Eatable{}

class Fruit implements Eatable{	public String toString() { return "Fruit"; }}
class Apple extends Fruit { public String toString() { return "Apple";}}
class Grape extends Fruit { public String toString() { return "Grape";}}
class Toy                 { public String toString() { return "Toy";}}

class FruitBox <T extends Fruit & Eatable> extends Box<T> {}
                   //  Eatable 생략가능.

class Box<T> {
	ArrayList<T> list = new ArrayList<T>(); // item 저장할 list
	
	void add(T item) { list.add(item);}  // 박스에 item추가
    T get(int i) {return list.get(i);}  // 박스에 item꺼낼때
    int size()   {return list.size();}  // 박스사이즈
    public String toString() { return list.toString();}
}
public class Example {
	public static void main(String[] args) {
		FruitBox<Fruit> fruitBox = new FruitBox<Fruit>();
		FruitBox<Apple> appleBox = new FruitBox<Apple>();
		FruitBox<Grape> grapeBox = new FruitBox<Grape>();
	//	FruitBox<Grape> grapeBox = new FruitBox<Apple>();  에러..타입불일치
	//	FruitBox<Toy> toyBox = new FruitBox<Toy>();  에러..
		Box<Toy> toyBox2 = new Box<Toy>(); 
		
		fruitBox.add(new Fruit());
		fruitBox.add(new Apple());
		fruitBox.add(new Grape());
		appleBox.add(new Apple());
	//	appleBox.add(new Grape());   에러..Grape 는 Apple 자손이아님.
		grapeBox.add(new Grape());
		
		System.out.println("fruitBox-"+fruitBox);
		System.out.println("appleBox-"+appleBox);
		System.out.println("grapeBox-"+grapeBox);	
		}		
	}

 

 

 

'SelfStudy > JAVA' 카테고리의 다른 글

JAVA (열거형)  (0) 2023.02.06
JAVA (제네릭 <?>, 형변환)  (0) 2023.02.05
JAVA (Collections), 컬렉션 요약정리.  (0) 2023.02.03
JAVA (HashMap)  (2) 2023.02.03
JAVA (HashSet, TreeSet)  (0) 2023.02.02
Comments