Notice
Recent Posts
Recent Comments
Link
«   2024/07   »
1 2 3 4 5 6
7 8 9 10 11 12 13
14 15 16 17 18 19 20
21 22 23 24 25 26 27
28 29 30 31
Tags
more
Archives
Today
Total
관리 메뉴

WON.dev

chapter05 : generic 본문

JAVA/chapter22_generic

chapter05 : generic

GAWON 2023. 5. 30. 18:40
package org.joonzis.ex;

import java.util.Arrays;

class Container <T>{
	private T[] items;
	
	@SuppressWarnings("unchecked")	// 명확하지 않은 타입 체크이지만, 더 이상 경고 하지마라 
	public Container(int capacity) {
		items = (T[])(new Object[capacity]);
	}
	
	public void add(T item) {	// setter
		// 순차적으로 순회하다가 빈자리가 발견되면 그 자리에 저장.
		// items 배열에 item 변수 저장
		for(int i=0; i<items.length; i++) {
			if(items[i] == null) {
				items[i] = item;
				break;
			}
		}
	}
	public T[] getItems() {
		return items;
	}
}
class Gun{
	private String model;
	public Gun(String model) {
		this.model = model;
	}
	@Override
	public String toString() {
		return model;
	}
}
public class Ex05_generic {
	public static void main(String[] args) {
		
		Container<Gun> con = new Container<>(10);
		con.add(new Gun("K2"));
		con.add(new Gun("K1"));
		con.add(new Gun("K5"));
		con.add(new Gun("M16"));
		
		System.out.println(Arrays.toString(con.getItems()));
		
		
	}
}

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

Test . Generic  (0) 2023.05.30
chapter06 : generic  (0) 2023.05.30
chapter04 : generic  (0) 2023.05.30
chapter03 : generic  (0) 2023.05.30
chapter02 : generic  (0) 2023.05.30