Java 사전학습_4
<Java 사전학습_4>
- 배열과 ArrayList(17강)
- 객체 배열 사용하기(18강)
- 다차원 배열(19강)
- ArrayList 클래스(20강)
- 연습문제 Q4~5
1. 배열과 ArrayList(17강)
배열을 쓰는 이유
정수 20개를 이용한 프로그램을 할 때 20 개의 정수 타입의 변수를 선언해야 함
(ex. int num1, num2, num3 … num20;)
이것이 비효율적이고 변수 관리도 힘들기에 배열 사용
배열은 동일한 자료형의 변수를 한꺼번에 순차적으로 관리할 수 있음
베열 선언하기
자료형[] 배열이름 = new 자료형[개수];
int[] arr = new int[10];
자료형 배열이름[] = new 자료형[개수];
int arr[] = new int [10];
배열 초기화
배열은 선언과 동시에 초기화할 수 있음
배열을 초기화할 떄는 배열의 개수를 명시하지 않음
아무런 초기화 값이 없이 선언만 한 경우 정수는 0, 실수는 0.0, 객체 배열은 null로 초기화됨
int[ ] studentIDs = new int[ ] {101, 102, 103}; //초기화하고 3개생성, int개수는 생략함
int[ ] studentIDs = new int[3] {101, 102, 103}; //개수를 명시하면 오류발생
int[ ] studentIDs = {101, 102, 103}; //int형 요소가 3개인 배열 생성
package array;
public class ArrayTest {
public static void main(String[] args) {
int[] numbers = new int[3];
numbers[0] = 1;
numbers[1] = 2;
numbers[2] = 3;
for(int i = 0; i<numbers.length; i++) {
System.out.println(numbers[i]); //1, 2, 3
}
int [] studentIDs = new int[5];
for(int i = 0; i<studentIDs.length; i++) {
System.out.println(studentIDs[i]); //0, 0, 0, 0, 0
}
}
}
배열 사용하기-[]
인덱스 혹은 첨자 연산자
배열의 위치를 지정하여 자료를 가져옴
모든 배열의 순서는 0부터 시작
n개의 배열은 0부터 n-1위치까지 자료가 존재
int[] num = new int[] {1, 2, 3, 4, 5}; //num[0]부터 num[4]까지 존재
배열을 초기화하고 출력하기
package array;
public class ArrayTest2 {
public static void main(String[] args) {
int[] numbers = new int[] {1, 2, 3}; //[]를 비우면 초기
for(int i = 0; i<3; i++) { //<=2보다 <3로 쓰는걸 선호(가독성)
// 결론적으로 숫자보단 numbers.length를 쓰는게 가장 좋다
System.out.println(numbers[i]); //1, 2, 3
}
}
}
배열의 길이와 유효한 요소 값
배열의 길이의 속성-length
자료가 있는 요소만 출력하려면 크기에 대한 저장을 따로 해야 함
package array;
public class ArrayTest3 {
public static void main(String[] args) {
double[] num = new double[5];
num[0] = 10.0;
num[1] = 20.0;
num[2] = 30.0;
double total = 1;
for(int i = 0; i < num.length; i++) {
System.out.println(num[i]); //10.0, 20.0, 30.0, 0.0, 0.0
total *= num[i];
}
System.out.println("total = " + total); //total = 0.0
// length로 쓰면 유효하지 않은 것까지 곱하기에 결과는 0이나옴
}
}
package array;
public class ArrayTest4 {
public static void main(String[] args) {
double[] num = new double[5];
int size = 0;
num[0] = 10.0; size++;
num[1] = 20.0; size++;
num[2] = 30.0; size++;
double total = 1;
for(int i = 0; i < size; i++) { //size를 넣어 유효한 값만 계산
System.out.println(num[i]); //10.0, 20.0, 30.0
total *= num[i];
}
System.out.println("total = " + total); //total = 6000.0
}
}
package array;
public class ArrayTest5 {
public static void main(String[] args) {
char[] alphabets = new char[26];
char ch = 'A'; //65
for(int i = 0; i <alphabets.length; i++, ch++) {
alphabets[i] = ch;
}
for(int i = 0; i <alphabets.length; i++, ch++) {
System.out.println(alphabets[i]); //A, B, C ... Z
}
}
}
2. 객체 배열 사용하기(18강)
객체 배열 만들기
참조 자료형을 선언하는 객체 배열
배열만 생성한 경우 요소는 null로 초기화됨
각 요소를 new를 활용하여 생성해 저장해야 함
package array;
public class Book {
private String bookName;
private String author;
public Book() {}
public Book(String bookName, String author) {
this.bookName = bookName;
this.author = author;
}
public String getBookName() {
return bookName;
}
public void setBookName(String bookName) {
this.bookName = bookName;
}
public String getAuthor() {
return author;
}
public void setAuthor(String author) {
this.author = author;
}
public void showBookInfo() {
System.out.println(bookName + "," + author);
}
}
package array;
public class BookArray {
public static void main(String[] args) {
Book[] library = new Book[5]; //책이 들어갈 자리 5개를 만듦
for(int i = 0; i < library.length; i++) {
System.out.println(library[i]); //null
}
library[0] = new Book("루카의 삶", "루팽구");
library[1] = new Book("잘 놀고 잘 먹는 법", "루이");
library[2] = new Book("초심자도 할 수 있는 나무타기", "루팽구");
library[3] = new Book("인간조련법", "루카");
library[4] = new Book("발톱관리론", "루카");
for(int i = 0; i < library.length; i++) {
System.out.println(library[i]); //주소값 출력
library[i].showBookInfo();
}
}
}
배열 복사하기
기존 배열과 같은 배열을 만들거나 배열이 꽉 찬 경우 더 큰 배열을 만들고 기존 배열 자료를 복사할 수 있음
붙여 넣을 위치보다 더 많은 개수를 붙여 넣는 경우 오류가 나니 주의할 것
System.arraycopy(src, srcPos, dest, destPos, length);
매개변수 | 설명 |
src | 복사할 배열 이름 |
srcPos | 복사할 배열의 첫 번쨰 위치 |
dest | 복사해서 붙여넣을 대상 배열 이름 |
destPos | 복사해서 대상 배열에 붙여넣기를 시작할 첫 번째 위치 |
length | src에서 dest로 자료를 복사할 요소 개수 |
int[] array1 = {10, 20, 30, 40, 50};
int [] array2 = {1, 2, 3, 4, 5};
System.arraycopy(array1, 0, array2, 1, 4);
//복사할 배열, 복사할 첫 위치, 대상 배열, 붙여넣을 첫 위치, 복사할 요소 개수
for(int i = 0; i < array2.length; i++) {
System.out.println(array2[i]); //1, 10, 20, 30, 40
}
객체 배열 복사하기
얕은 복사
배열 요소의 주소만 복사되므로 배열 요소가 변경되면 복사된 배열의 값도 변경
package array;
public class ObjectCopy {
public static void main(String[] args) {
Book[] bookArray1 = new Book[3];
Book[] bookArray2 = new Book[3];
bookArray1[0] = new Book("루카의 요리교실", "루카");
bookArray1[1] = new Book("약 먹는 법", "루이");
bookArray1[2] = new Book("모어 츄르", "루팽");
System.arraycopy(bookArray1, 0, bookArray2, 0, 3); //값이 아니라 주소가 복사됨, 얕은복사
for(int i = 0; i < bookArray2.length; i++) {
bookArray2[i].showBookInfo();
}
bookArray1[0].setBookName("체인지");
bookArray1[0].setAuthor("제이");
for(int i = 0; i < bookArray2.length; i++) {
bookArray1[i].showBookInfo();
}
System.out.println("======");
for(int i = 0; i < bookArray2.length; i++) {
bookArray2[i].showBookInfo();
//그러므로 배열의 요소 값을 변경하는 경우 둘 다 변경됨
}
}
}
깊은 복사
인스턴스를 다시 생성해야 함
서로 다른 인스턴스 메모리를 요소로 가지게 됨
package array;
public class ObjectCopy2 {
public static void main(String[] args) {
Book[] bookArray1 = new Book[3];
Book[] bookArray2 = new Book[3];
bookArray1[0] = new Book("루카의 요리교실", "루카");
bookArray1[1] = new Book("약 먹는 법", "루이");
bookArray1[2] = new Book("모어 츄르", "루팽");
bookArray2[0] = new Book();
bookArray2[1] = new Book();
bookArray2[2] = new Book();
for(int i = 0; i < bookArray1.length; i++) {
bookArray2[i].setAuthor(bookArray1[i].getAuthor());
bookArray2[i].setBookName(bookArray1[i].getBookName());
}
bookArray1[0].setBookName("체인지");
bookArray1[0].setAuthor("제이");
for(int i = 0; i < bookArray2.length; i++) {
bookArray1[i].showBookInfo();
}
System.out.println("======");
for(int i = 0; i < bookArray2.length; i++) {
bookArray2[i].showBookInfo();
//인스턴스가 따로이기에 1을 바꿔도 2에 영향없음, 깊은복사
}
}
}
향상된 for문(enhanced for loop)
배열 요소의 처음부터 끝까지 모든 요소를 참조할 때 편리한 반복문
for(변수 : 배열) {
반복 실행문;
}
String[] strArr = {"Java", "Android", "C"};
for(int i = 0; i < strArr.length; i++) { //그냥 for문
System.out.println(strArr[i]);
}
for(String s : strArr) { //향상된 for문, 모든 배열 순회
System.out.println(s); //변수s에 배열의 각 요소가 대입
}
int[] arr = {1, 2, 3, 4, 5};
for(int num : arr) {
System.out.println(num);
}
3. 다차원 배열(19강)
다차원 배열
2차원 이상의 배열
지도, 게임 등 평면이나 공간을 구현할 때 많이 사용
이차원 배열의 선언과 구조
int[][] arr = new int[2][3]; //자료형, 배열이름, 행 개수, 열 개수
선언과 초기화
int[][] arr = {{1, 2, 3,}, {4, 5, 6}};
다차원 배열 사용하기
전체 모든 요소를 출력하려면 중첩된 for문을 사용해야 함
package array;
public class TowDimensionArray {
public static void main(String[] args) {
// int[][] arr = new int[2][3]; //행, 열
int[][] arr = {{1, 2, 3}, {4, 5, 6}}; //2행3열, 초기화와 선언
System.out.println(arr.length); //2, 길이는 행의 수
System.out.println(arr[0].length); //3, 행기준 0번째줄의 길이
System.out.println(arr[1].length); //3, 행기준 1번째의 길이
for(int i = 0; i < arr.length; i++) { //i < 2, 행의 수
for(int j = 0; j < arr[i].length; j++) //j < 3, 열의 수
System.out.println(arr[i][j]);
//0.0, 0.1, 0.2, 1.0, 1.1, 1.2 배열 자리의 수 1~6이 출력됨
}
}
}
4. ArrayList 클래스(20강)
ArrayList 클래스
기존 배열은 길이를 정하여 선언하므로 사용 중 부족한 경우 다른 배열로 복사하는 코드를 직접 구현해야 함
중간의 요소가 삭제되거나 삽입되는 경우도 나머지 요소를 조정하는 코드를 구현해야 함
ArrayList클래스는 자바에서 제공되는 객체 배열이 구현된 클래스
여러 메서드와 속성 등을 사용하여 객체 배열을 편리하게 관리할 수 있음
가장 많이 사용하는 객체 배열 클래스
ArrayList 클래스 주요 메서드
요소를 추가하거나 제거할 때 각 내부에서 코드가 모두 구현되어 있으므로 배열을 직접 선언하여 사용하는 것보다 편리함
메서드 | 설명 |
boolean add(E e) | 요소 하나를 배열에 추가합니다. E는 요소의 자료형을 의미합니다. |
int size() | 배열에 추가된 요소 전체 개수를 반환합니다. |
E get(int index) | 배열의 index 위치에 있는 요소값을 반환합니다. |
E remove(int index) | 배열의 index위치에 있는 요소 값을 제거하고 그 값을 반환합니다. |
boolean isEmpty() | 배열이 비어있는지 확인합니다. |
package arraylist;
import java.util.ArrayList;
public class ArrayListTest {
public static void main(String[] args) {
ArrayList<String> list = new ArrayList<String>();
list.add("aaa");
list.add("bbb");
list.add("ccc");
for(String s : list) {
System.out.println(s);
}
for(int i = 0; i < list.size(); i++) {
String s = list.get(i);
}
}
}
ArrayList 클래스 사용하기
ArrayList<E> 배열이름 = new ArrayList<E>();
//사용할 객체를 E 위치에 넣고 ArrayList메서드를 활용하여 추가하거나 참조할 수 있음
package arraylist;
import java.util.ArrayList;
public class Student {
private int studentID;
private String studentName;
private ArrayList<Subject> subjectList;
public Student(int studentID, String studentName) {
this.studentID = studentID;
this.studentName = studentName;
subjectList = new ArrayList<Subject>();
}
public void addSubject(String name, int score) {
Subject subject = new Subject();
subject.setName(name);
subject.setScorePoint(score);
subjectList.add(subject);
}
public void showStudentInfo() {
int total = 0;
for(Subject subject : subjectList) {
total += subject.getScorePoint();
System.out.println("학생 " + studentName + "님의 " + subject.getName()
+ " 과목의 성적은 " + subject.getScorePoint() + "점 입니다.");
}
System.out.println("학생 " + studentName + "님의 총점은 " + total + "점 입니다.");
}
}
package arraylist;
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;
}
}
package arraylist;
public class StudentTest {
public static void main(String[] args) {
Student student1 = new Student(1001, "Luppang");
student1.addSubject("사료학", 80);
student1.addSubject("나무타기", 100);
student1.showStudentInfo();
System.out.println("========");
Student student2 = new Student(1002, "Luka");
student2.addSubject("사료학", 90);
student2.addSubject("나무타기", 70);
student2.addSubject("사냥", 100);
student2.showStudentInfo();
}
}
5. 연습문제 Q4~5
반복문을 사용하여 별 찍기
*
***
*****
*******
package practice;
public class Q4 {
public static void main(String[] args) {
int lineCount = 4;
int starCount = 1;
int spaceCount = lineCount/2 + 1;
for(int i = 0; i < lineCount; i++) {
for(int j = 0; j < spaceCount; j++) { //왼쪽공백
System.out.print(" ");
}
for(int j = 0; j < starCount; j++) { //별
System.out.print("*"); //println쓰면 줄바꿈되니 주의!
}
for(int j = 0; j < spaceCount; j++) { //오른쪽공백
System.out.print(" ");
}
spaceCount -= 1;
starCount += 2;
System.out.println();
}
}
}
반복문과 조건문을 사용하여 별 찍기
*
***
*****
*******
*****
***
*
package practice;
public class Q5 {
public static void main(String[] args) {
int lineCount = 7;
int starCount = 1;
int spaceCount = lineCount/2 + 1;
for(int i = 0; i < lineCount; i++) {
for(int j = 0; j < spaceCount; j++) {
System.out.print(" ");
}
for(int j = 0; j < starCount; j++) { //별
System.out.print("*");
}
for(int j = 0; j < spaceCount; j++) {
System.out.print(" ");
}
if(i < lineCount/2) { //0, 1, 2일때
spaceCount -= 1;
starCount += 2;
}
else { //3, 4, 5일때
spaceCount += 1;
starCount -= 2;
}
System.out.println();
}
}
}