본문 바로가기

IT/자바

제네릭 타입 설명

MyArrayList.java

MyMain_Generic_Test.java

package myutil;

public class MyArrayList<T> {

	T [] data;

	// 변수 초기화 역활
	public MyArrayList() {
		data = null;
	}

	public int size() {
		return (data == null) ? 0 : data.length;
	}

	public void add(T newObj) {
		System.out.println("="+size());
		// 임시배열 : 기존갯수보다+1 생성
		T [] im = ( T[] )new Object[size() + 1];//0, 1(컴텨) = 1(사람)
		System.out.println("----------------");
		// 기존값을 새로만들 배열에 옮기기
		for (int i=0; i<size(); i++) {
			im[i] = data[i];
		}
		/*
		 	im[0] = data[0] => im[0]:100, data[0]:100
		*/

		// 임시배열의 마지막에 새로운 객체를 넣는다
		im[size()] = newObj;

		// 임시배열을 data에 넣는다
		data = im;

	}

	// 예외처리 위임(양도)
	public Object get(int index) throws Exception {

		if (index < 0 || index >= size()) {

			String msg = String.format("첨자범위:0~%d까지 들어온 값 : %d", size() - 1, index);
			// 던저진 예외를 get이라 메소드를 사용하는 사용자가 받아서 처리해라
			// 예외처리 위임(양도)
			throw new Exception(msg);
		}

		return data[index];
	}

	public void remove(int index) throws Exception {

		if (index < 0 || index >= size()) {

			String msg = String.format("첨자범위:0~%d까지 들어온 값 : %d", size() - 1, index);
			// 던저진 예외를 get이라 메소드를 사용하는 사용자가 받아서 처리해라
			// 예외처리 위임(양도)
			throw new Exception(msg);
		}

		// 삭제 로직....

		// 데이터가 1개남았으면
		if (size() == 1) {
			data = null;
			return;
		}

		// 임시배열의갯수 = 기존배열의갯수-1
		T[] im = (T[])new Object[size() - 1];

		// 기존배열의 삭제인덱스를 제외한 값을 임시배열에 옮기기
		for (int i = 0; i < size() - 1; i++) {
			if (i < index)
				im[i] = data[i];
			else
				im[i] = data[i + 1];
		}

		// 임시를 data로 치환
		data = im;

	}

}
package mymain;

import java.util.ArrayList;

import myutil.MyArrayList;

public class MyMain_Generic_Test {

	public static void main(String[] args) {

		//5.0 이후부터 사용 가능
		//저장 타입을 지정하지 않았을때 문제점
		ArrayList list = new ArrayList();
		list.add("물");				//0
		list.add(new Integer(100));	//1
		list.add(new Double(1.0));	//2
		list.add(new Boolean(true));//3
		
		//해당타입을 캐스팅해서 사용해야 된다
		String str = (String)list.get(0);
		
		//타입체크해서 해당자료형으로 형변환해서 사용(불필요한...)
		Integer nob = null;
		if(list.get(1) instanceof Integer)
			nob = (Integer)list.get(1);
		
		//
		ArrayList<String> fruit_list = new ArrayList<String>();
		fruit_list.add("사과");//0
		fruit_list.add("수박");//1
		fruit_list.add("참외");//2
		//fruit_list.add(new Integer(100));
		
		String fruit = fruit_list.get(0);
		
		//저장타입을 Integer만 저장되도록 설정
		ArrayList<Integer> month_list = new ArrayList<Integer>();
		month_list.add(31);
		month_list.add(28);
		month_list.add(31);
		
		//month_list.add("4월");
		
		
		MyArrayList<String> name_list = new MyArrayList<String>();
		name_list.add("일길동");
		//name_list.add(new Integer(100));
		
		//Generic은 객체만 지정할 수 있다.
		//MyArrayList<int> int_list = new MyArrayList<int>(); (X)
		MyArrayList<Integer> int_list = new MyArrayList<Integer>();		
		
		
		
	}

}