이번시간에는 List에 대해 알아보도록 하겠습니다.

List는 레퍼런스 즉 참조형 입니다.

참조형이 머냐....글쎄 머라고 설명해야 좋을까???

일단 아래 샘플 소스와 그결과를 가지고 설명해 보겠습니다.

 

import java.util.ArrayList;
import java.util.List;


public class ListTest {

	/**
	 * @param args
	 */
	public static void main(String[] args) {
		// TODO Auto-generated method stub
		
		// 문자열을 담을 리스트 생성
		List<String> strLstA = new ArrayList<String>();
		
		// 리스트에 문자열을 넣음.
		strLstA.add("a");
		strLstA.add("c");
		strLstA.add("d");
		strLstA.add("e");
		System.out.println("strLstA = " +strLstA);
		System.out.println();
		
		// B문자열 리스트를 생성합니다.
		List<String> strLstB = new ArrayList<String>();
		// A문자열 리스트의 해시코드와 B문자열 리스트의 해시코드 출력합니다. 
		System.out.println("strLstA HashCode = " + strLstA.hashCode());
		System.out.println("strLstB HashCode = " + strLstB.hashCode());
		System.out.println();
		
		// B문자열 리스트에 A문자열 리스트를 대입한다.
		strLstB = strLstA;
		
		// A문자열 리스트의 해시코드와 B문자열 리스트의 해시코드 출력합니다. 
		System.out.println("strLstA HashCode = " + strLstA.hashCode());
		System.out.println("strLstB HashCode = " + strLstB.hashCode());
		System.out.println();
		
		// B문자열 리스트에 문자열을 추가한다.
		strLstB.add("F");
		
		// A문자열 리스트에 문자열을 추가한다.
		strLstA.add("E");
		
		// A문자열 리스트와 B문자열 리스트를 출력합니다. 
		System.out.println("strLstA = " + strLstA);
		System.out.println("strLstB = " + strLstB);
		System.out.println();
		
		// A문자열 리스트의 해시코드와 B문자열 리스트의 해시코드 출력합니다. 
		System.out.println("strLstA HashCode = " + strLstA.hashCode());
		System.out.println("strLstB HashCode = " + strLstB.hashCode());

	}

}

 

[실행결과]

strLstA = [a, c, d, e] <- A문자열 리스트의 결과를 일단표시 했습니다. strLstA HashCode = 3911588 <- A문자열 리스트의 해시코드 strLstB HashCode = 1 <- B문자열 리스트를 생성 했을때 해시코드 strLstA HashCode = 3911588 <- A문자열 리스트의 해시코드 strLstB HashCode = 3911588 <- A문자열 리스트를 B문자열 리스트에 대입한후의 해시코드

A문자열 리스트와 B문자열 리스트에 해시코드가 같아짐. strLstA = [a, c, d, e, F, E] <- B문자열 리스트에 'F'문자열을추가, A문자열 리스트에 'E'문자열을추가

strLstB = [a, c, d, e, F, E] <- B문자열 리스트에 'F'문자열을추가, A문자열 리스트에 'E'문자열을추가 A문자열 리스트와 B문자열 리스트에 둘중에 하나가 값이 바뀌면 같이 바뀌게됨. strLstA HashCode = -535928989 <- 값을 추가하면서 해시코드가 바뀜

strLstB HashCode = -535928989 <- 값을 추가하면서 해시코드가 바뀜

위 내용을 정리해보면 List같은 참조형 변수는 대입할때 값을 대입 시키는게 아니라 참조하고 있는곳을 대입시킵니다. 

즉, 참조하는 곳이 같아진다는 뜻이죠.

참조하는곳이 같아진다는 것은 값도 같아진다 라는 뜻이겠죠!

 List변수 끼리 대입한후 어느 하나가 바뀌면 같이 바뀌어 버리게 됩니다.

List뿐만 아니라 Map도 같은 성격을 가지고 있습니다.

 

다 아시는 분도 계시겠지만 틀린부분이 있으면 지적해주시고, 모르고 계신분 들이 있다면

참고 하셨으면 합니다.

 

감사합니다.