JAVA 04 : 배열, ArrayList,

LeeWonjin·2022년 7월 18일

2022 백엔드스터디

목록 보기
4/20

Do it! 자바 프로그래밍 입문 7장

배열 개요 및 일차원 배열

동일한 자료형을 저장할 수 있는 논리적/물리적으로 모두 연속된 자료구조
배열은 사용하기 전 고정길이로 선언한다.

선언

아래 방법으로 선언할 수 있다.

자료형[] 식별자 = new 자료형[길이];
자료형 식별자[] = new 자료형[길이];

아래와 같이 선언과 동시에 초기화 할 수 있다.

자료형[] 식별자 = new 자료형[] { 원소1, 원소2, 원소3, ... };
자료형 식별자[] = new 자료형[] { 원소1, 원소2, 원소3, ... };

초기화 되지 않은 경우 초기값으로 0, 0.0, null 등이 들어간다.

접근

  • 원시자료형(int) 배열
public class helloworld {
	static public void main(String[] args) {
		// arr
		int[] arr = new int[3];
		for(int i=0; i<3; i++)
			arr[i] = i*2;
		for(int i=0; i<3; i++)
			System.out.println(arr[i]); // 0 2 4
		
		// arr2
	    int[] arr2 = {1, 2, 3};
	    for(int i=0; i<3; i++)
	    	System.out.println(arr2[i]); // 1 2 3
	}
}
  • 참조자료형(Gorani) 배열
class Gorani {
	public String name;
	
	public Gorani (String name) {
		this.name = name;
	}
}

public class helloworld {
	static public void main(String[] args) {
		// declare arr
		Gorani[] arr = new Gorani[3];
		
		// print arr
		for(int i=0; i<arr.length; i++)
			System.out.println(arr[i]); // null
		
		// initialize arr as gorani instance
		for(int i=0; i<arr.length; i++)
			arr[i] = new Gorani(Integer.toString(i));
		
		// print arr
		for(int i=0; i<arr.length; i++)
			System.out.println("I am " + arr[i].name);
			// I am 0, I am 1, I am 2
	}
}

향상된 for문 (enhanced for loop)

배열 내의 모든 원소를 순회한다.

for(변수식별자 : 배열 식별자) {
  내용
}

public class helloworld {
	static public void main(String[] args) {
		int[] arr = new int[] { 5, 10, 15, 20, 25 };
		
		for(int item : arr)
			System.out.println(item); // 5 10 15 20 25
	}
}

배열 복사

  • System.arraycopy메소드를 이용한 복사
// 원형
static void arraycopy(Object src, int srcPos, Object dest, int destPos, int length)

// 원시자료형의 복사
public class helloworld {
	static public void main(String[] args) {
		int[] arr1 = new int[] { 5, 10, 15, 20, 25 };
		int[] arr2 = new int[3];
		
		System.arraycopy(arr1, 1, arr2, 0, 3);
		// arr1[1]~arr[3]까지 arr2[0]~arr2[2]에 복사
		
		for(int i=0; i<arr2.length; i++)
			System.out.println(arr2[i]); // 10 15 20
	}
}

참조자료형을 복사하는 경우 얕은복사가 일어나 의도하지 않은 결과가 일어날 수 있으므로, 필요한경우 깊은복사를 수행해야 함.

  • 객체 배열에 대한 깊은복사
class Gorani {
	public String name;
	
	public Gorani (String name) {
		this.name = name;
	}
}

public class helloworld {
	static public void main(String[] args) {
		Gorani[] src = new Gorani[3];
		Gorani[] dest_shallow = new Gorani[3];
		Gorani[] dest_deep = new Gorani[3];
		
		src[0] = new Gorani("LEE");
		src[1] = new Gorani("KIM");
		src[2] = new Gorani("JANG");
		
		// shallow copy : src --> dest_shallow
		System.arraycopy(src, 0, dest_shallow, 0, src.length);
		dest_shallow[2].name = "Shallow";
		for(Gorani item : src)
			System.out.println(item.name); // LEE KIM Shallow
		for(Gorani item : dest_shallow)
			System.out.println(item.name); // LEE KIM Shallow
		System.out.println();
		
		// deep copy : src --> dest_deep
		for(int i=0; i<src.length; i++)
			dest_deep[i] = new Gorani(src[i].name);
		dest_deep[2].name = "Deep";
		for(Gorani item : src)
			System.out.println(item.name); // LEE KIM Shallow
		for(Gorani item : dest_deep)
			System.out.println(item.name); // LEE KIM Deep
	}
}

이차원 배열

  • 선언
자료형[][] 배열식별자 = new 자료형[행_길이][열_길이];
  • 선언과 동시에 초기화
자료형[][] 배열식별자 = { 
  {원소0-0, 원소0-1, 원소0-2}, 
  {원소1-0, 원소1-1, 원소1-2} 
};
  • 순회
public class helloworld {
	static public void main(String[] args) {
		int[][] arr = { 
				{10, 20, 30, 40}, 
				{500, 1000, 1500, 2000} 
		};
		
		for(int[] row : arr) {
			for(int item : row)
				System.out.println(item);
			System.out.println();
		}
		// 10 20 30 40
		// 500 1000 1500 2000
	}
}

ArrayList 클래스

객체배열을 사용할 때 빈번하게 사용하는 클래스
길이가 변해야 하는 경우 편리.

선언

ArrayList<E> 식별자 = new ArrayList<E>();

** E는 자료형

주요 메소드

  • boolean add(E e)
  • int size()
  • E get(int index)
  • E remove(int index)
  • boolean isEmpty()
import java.util.ArrayList;

class Gorani {
	public String name;
	
	public Gorani (String name) {
		this.name = name;
	}
}

public class helloworld {
	static public void main(String[] args) {
		ArrayList<Gorani> list = new ArrayList<Gorani>();
		System.out.println(list.size()); // 0
		System.out.println(list.isEmpty()); // true
		System.out.println();
		
		list.add(new Gorani("First"));
		list.add(new Gorani("Second"));
		list.add(new Gorani("Third"));
		
		for(Gorani item : list)
			System.out.println(item.name); // First Second Thrid
		System.out.println(list.get(2)); // Gorani@(어떤 값)
		System.out.println(list.size()); // 3
		System.out.println(list.isEmpty()); // false
		System.out.println();
		
		list.remove(1);
		for(Gorani item : list)
			System.out.println(item.name); // First Third
	}
}
profile
노는게 제일 좋습니다.

0개의 댓글