본문 바로가기
컴퓨터/java

제너릭, ArrayList

by 싱판다 2017. 7. 31.

<> -> 이 부분이 제너릭 어느 형 타입을 담을 것인지를 지정해주는 부분 

// GenericList<Object> list = new GenericList<Object>();

이런 식으로 생성해준다.

ArrayList는 배열이 늘어나면 늘어날 수록 저절로 공간을 늘이는 작업을 해준다.

ArrayList역시 ArrayList<> 이렇게 제너릭을 사용하여 생성해주면 원하는 타입을 담아내는 ArrayList를 만들 수 있다.



궁금점


다음과 같은 소스가 있다고 하자.

public class GenericList <test>{

private test[] list;

private int index;

private int capacity;

private int current;

public GenericList(){

index = 0;

list = (test[]) new Object[3];

capacity = list.length;

current = -1;

}

public void add(test exam) {

if (index >= capacity) {

test[] temp = (test[])new Object[capacity + 2];

for (int i=0; i<list.length; i++)

temp[i] = list[i];

list  = temp;

capacity = list.length;

}

list[index++] = exam;

}


public test get(int i) {

return list[i];

}


public int size() {

return index;

}


public boolean hasNext() {

/*if((++current) == index){

return false;

}

else

return true;*/

return size() == (++current)? false:true;

}



public test next() {

return list[current];

}

}


메인에서 

GenericList list = new GenericList();


list.add(3);

list.add("hello");

for(int i = 0;i<list.size(); i++){

System.out.println(list.get(i));

}


이렇게 제너릭으로 선언해주지 않았을 때 어떻게 넘어오고 어떻게 출력이 가능한 것일까

Object로 선언했을 때 출력 부분에 형변환을 해줘야 하는 불편이 있다. 어느 자료형인지 모르기 때문.

//but, Object 로 get() 했을 때 출력을 하긴 했다.

제너릭은 문맥상 어느 자료형인지 알 수 있다고 했는데. 그런건가.


public void add(test exam) {

if (index >= capacity) {

test[] temp = (test[])new Object[capacity + 2];

for (int i=0; i<list.length; i++)

temp[i] = list[i];

list  = temp;

capacity = list.length;

}

list[index++] = exam;

}


오브젝트에 인트형을 넘긴다면 인트형을 저장하고 스트링이면 스트링을 저장한다.....................

근데 무슨 자료형인지 모를 텐데? 출력할 때 이걸 기억하나? 자기가 어떤 자료형인지 알고 있는건가?



출력할 땐 무슨 자료형인지 나타나지 않아도 되지만 연산될 때는 문제인듯 하다.

System.out.println((lists.get(0) + lists.get(1)); -> 에러가 난다.







'컴퓨터 > java' 카테고리의 다른 글

System.out.println  (0) 2017.07.31
채팅 프로그램 만들기  (0) 2017.07.31
0728 수업 / Object 클래스  (0) 2017.07.28
0728 수업 / 배열을 늘릴 수 있는 방법 1  (0) 2017.07.28
문자열 쪼개기 등  (0) 2017.07.28

댓글