본문 바로가기
Java

Java 객체지향 입문 / 배열, 객체 배열, 2차원 배열, ArrayList

by 리잼 2022. 11. 16.
반응형

20. 배열( Array )

배열이란?

  • 동일한 자료형의 순차적 자료 구조
  • 인덱스 연산자 [ ]를 이용하여 빠른 참조가 가능
  • 물리적 위치와 논리적 위치가 동일
  • 배열의 순서는 0부터 시작
  • 자바에서는 객체 배열을 구현한 ArrayList를 많이 활용한다

배열 선언과 초기화

배열 선언하기

int[] arr1 = new int[10];
int arr2[] = new int[10];

배열

배열 초기화하기

  • 배열은 선언과 동시에 자료형에 따라 초기화 됨 ( 정수는 0, 실수는 0.0, 객체는 null )
    필요데 따라 초기값을 지정할 수 있음
int[] number = new int[] {10, 20, 30}; // 개수 생략해야함

int[] number = {10,20,30}; // new int[] 생략 가능

int[] ids;
ids = new int[] {10,20,30}; // 선언 후 배열을 생성하는 경우는 new int[] 생략 가능

배열 사용하기

  • [ ] 인덱스 연산자 활용 - 배열 요소가 저장된 메모리의 위치를 연산하여 찾아 줌
  • 배열을 이용하여 합을 구하기

배열의 길이와 요소의 개수는 동일하지 않다

  • 배열을 선언하면 개수만큼 메모리가 할당되지만, 실제 요소(데이터)가 없는 경우도 있다
  • 배열의 length 속성은 배열의 개수를 반환해주기 때문에 요소의 개수와는 다름

length를 활용하여 오류가 가는 경우

double[] dArr = new double[5];

dArr[0] = 1.1;
dArr[1] = 2.1;
dArr[2] = 3.1;

double mtotal = 1;
for(int i=0; i<dArr.length; i++){
	mtotal *= dArr[i];
   }
   
System.out.println(mtotal);

요소의 개수에 대한 변수(count)를 따로 유지

double[] dArr = new double[5];
int count = 0;
dArr[0] = 1.1; count++;
dArr[1] = 2.1; count++;
dArr[2] = 3.1; count++;

double mtotal = 1;
for(int i=0; i<count; i++){
	mtotal *= dArr[i];
}

System.out.println(mtotal);

문자 배열을 만들어 A-Z까지 배열에 저장하고 다시 출력하기

public class CharArrayTest {

	public static void main(String[] args) {

		char[] alpahbets = new char[26];
		char ch = 'A';
		
		for(int i=0; i<alpahbets.length; i++) {
			alpahbets[i] = ch++;
		}
		
		for( char alpha : alpahbets ) {
			System.out.println(alpha + "," + (int)alpha);
		}
	}

}

향상된 for문 사용하기

배열의 n개 요소를 0부터 n-1까지 순차적으로 순회할 때 간단하게 사용이 가능

for( 변수 : 배열) {

}

21. 객체 배열 사용하기

객체 배열 선언과 구현

  • 기본 자료형 배열은 선언과 동시에 배열의 크기만큼 메모리가 할당되지만, 객체 배열의 경우엔 요소가 되는 객체의 주소가 들어갈 (4byte, 8byte) 메모리만 할당되고 (null) 각 요소 객체는 생성하여 저장해야함

Book.java

public class Book {

	private String title;
	private String author;
	
	public Book() {};
	
	public Book(String title, String author) {
		this.title = title;
		this.author = author;
	}
	
	public String getTitle() {
		return title;
	}

	public void setTitle(String title) {
		this.title = title;
	}

	public String getAuthor() {
		return author;
	}

	public void setAuthor(String author) {
		this.author = author;
	}
	
	public void showInfo() {
		System.out.println(title + "," + author);
	}
	
}

BookTest.java

public class BookTest {

	public static void main(String[] args) {

		Book[] library = new Book[5];
		
//		for(int i=0; i<library.length; i++) {
//			System.out.println(library[i]);
//		}
		
		library[0] = new Book("가나다라1", "홍길동");
		library[1] = new Book("가나다라2", "임길동");
		library[2] = new Book("가나다라3", "최길동");
		library[3] = new Book("가나다라4", "이길동");
		library[4] = new Book("가나다라5", "김길동");
		
		for(Book book:library) {
			System.out.println(book);
			book.showInfo();
		}
		
	}

}

출력 결과

객체 배열 복사

  • System.arrayCop(src, srcPos, dest, destPos, length) 자바에서 제공되는 배열 복사 메서드
  • 얕은 복사
    객체 주소만 복사되어 한쪽 배열의 요소를 수정하면 같이 수정됨
    즉, 두 배열이 같은 객체를 가리킴

ObjectCopyTest.java

public class ObjectCopyTest {

	public static void main(String[] args) {

		Book[] library = new Book[5];
		Book[] copyLibrary = new Book[5];
		
		library[0] = new Book("가나다라1", "홍길동");
		library[1] = new Book("가나다라2", "임길동");
		library[2] = new Book("가나다라3", "최길동");
		library[3] = new Book("가나다라4", "이길동");
		library[4] = new Book("가나다라5", "김길동");
        
		System.arraycopy(library, 0, copyLibrary, 0, 5); 
		// library 0번째부터, copyLibrary 0부터 5까지 복사
		System.out.println("== library ==");
		for(Book book:library) {
			System.out.println(book);
			book.showInfo();
		}
		
		System.out.println("== copyLibrary ==");
		for(Book book:copyLibrary) {
			System.out.println(book);
			book.showInfo();
		}
	}

}

  • 깊은 복사
    각각의 객체를 생성하여 그 객체의 값을 복사하여 배열이 서로 다른 객체를 가리키도록 함
public class ObjectCopyTest2 {

	public static void main(String[] args) {

		Book[] library = new Book[5];
		Book[] copyLibrary = new Book[5];
		
		library[0] = new Book("가나다라1", "홍길동");
		library[1] = new Book("가나다라2", "임길동");
		library[2] = new Book("가나다라3", "최길동");
		library[3] = new Book("가나다라4", "이길동");
		library[4] = new Book("가나다라5", "김길동");
		
		copyLibrary[0] = new Book();
		copyLibrary[1] = new Book();
		copyLibrary[2] = new Book();
		copyLibrary[3] = new Book();
		copyLibrary[4] = new Book();
		
		for(int i=0; i<library.length; i++)	{
			copyLibrary[i].setAuthor(library[i].getAuthor());
			copyLibrary[i].setTitle(library[i].getTitle());
		}
		
		
		System.out.println("== library ==");
		for(Book book:library) {
			System.out.println(book);
			book.showInfo();
		}
		
		System.out.println("== copyLibrary ==");
		for(Book book:copyLibrary) {
			System.out.println(book);
			book.showInfo();
		}
	}

}


22. 2차원 배열 사용하기

다차원 배열

  • 이차원 이상으로 구현 된 배열
  • 평면 (2차원 배열)이나 공간(3차원 배열)을 활용한 프로그램 구현

2차원 배열 예제

TwoDimensionTest.java

public class TwoDimensionTest {

	public static void main(String[] args) {

		int[][] arr = {{1,2,3}, {1,2,3,4}};
		
		int i,j;
		
		for(i=0; i<arr.length; i++) {
			
			for(j=0; j<arr[i].length; j++) {
				System.out.print(arr[i][j] + ",");
			}
			System.out.println("\t"+arr[i].length);
		}
		
	}

}

출력 결과


23. 객체 배열을 구현한 클래스 ArrayList

java.util 패키지에서 제공되는 ArrayList

  • 기존의 배열 선언과 사용 방식은 배열의 길이를 정하고 요소의 개수가 배열의 길이보다 커지면 배열을 재할당하고 복사해야했음
  • 배열의 요소를 추가하거나 삭제하면 다른 요소들이 이동에 대한 구현을 해야 함
  • ArrayList는 객체 배열을 좀 더 효율적으로 관리하기 위해 자바에서 제공해주는 클래스
  • 이미 많은 메서드들이 최적의 알고리즘으로 구현되어 있어 각 메서드의 사용 방법만 익히면 유용하게 사용가능

ArrayList의 주요 메서드

ArrayListTest.java

import java.util.ArrayList;
import ch21.Book;

public class ArrayListTest {

	public static void main(String[] args) {

		ArrayList<Book> library = new ArrayList<>();
		
		library.add(new Book("태백산맥1", "조정래"));
		library.add(new Book("태백산맥2", "조정래"));
		library.add(new Book("태백산맥3", "조정래"));
		library.add(new Book("태백산맥4", "조정래"));
		library.add(new Book("태백산맥5", "조정래"));
		
		for(int i=0; i<library.size(); i ++) {
			library.get(i).showInfo();
		}
		
	}

}

 

24. ArrayList를 활용한 성적 산출 프로그램

예제 시나리오

Student.java

import java.util.ArrayList;

public class Student {

	int studentID;
	String studentName;
	
	ArrayList<Subject> subjectsList;
	
	Student(int studentID, String studentName) {
		this.studentID = studentID;
		this.studentName = studentName;
		
		subjectsList = new ArrayList<>();
	}
	
	public void addSubject(String name, int point) {
		Subject subject = new Subject();
		subject.setName(name);
		subject.setScorePoint(point);
		
		subjectsList.add(subject);
	}
		
	public void showScoreInfo() {

		int total = 0;
		for( Subject subject : subjectsList ) {
			total += subject.getScorePoint();
			System.out.println(studentName + "학생의 " + subject.getName() + " 과목의 성적은 " + subject.getScorePoint() + " 입니다.");
		}
		System.out.println( studentName + " 학생의 총점은 " + total +" 점 입니다.");
		
	}
}

Subject.java

public class Subject {

	private String name;
	private int scorePoint;
	
	public String getName() {
		return name;
	}
	public void setName(String name) {
		this.name = name;
	}
	public int getScorePoint() {
		return scorePoint;
	}
	public void setScorePoint(int scorePoint) {
		this.scorePoint = scorePoint;
	}
}

StudentSubjectTest.java

public class StudentSubjectTest {

	public static void main(String[] args) {

		Student studentLee = new Student(1001, "Lee");
		Student studentKim = new Student(1002, "Kim");
		
		studentLee.addSubject("국어", 100);
		studentLee.addSubject("수학", 50);	
		
		studentKim.addSubject("국어", 70);
		studentKim.addSubject("수학", 85);
		studentKim.addSubject("영어", 100);
		
		studentLee.showScoreInfo();
		System.out.println("================");
		studentKim.showScoreInfo();
	}

}

 

반응형