나 java봐랏 6일차(배열)

김혜성·2021년 7월 19일
0

나 java봐랏

목록 보기
6/7

배열과 ArrayList

ArrayList는 JDK 제공 Class
배열의 기본적인 내용은 생략..
파이썬, C언어, 자구...그만...

package array;

public class ArrayTest {

	public static void main(String[] args) {
		int[] numbers = new int[] {0,1,2};//초기화되는 만큼 메모리 생성
		int[] numbers2 = {0,1,2}; //이렇게도 가능
		int[] num3 = new int[5]; //다 0으로 초기화됨
		System.out.println(numbers.length);
		
		numbers2[0] = 4;
		numbers2[1] = 5;
		numbers2[2] = 6;
		
		for(int i=0;i<numbers2.length;i++) {
			System.out.println(numbers2[i]);
		}
		for(int i=0;i<num3.length;i++) {
			System.out.println(num3[i]);
		}
	}

}
package array;



public class ArrayTest2 {
	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]);
		}
		System.out.println(alphabets);
	}
	
}

객체 배열

참조 자료형을 사용하는 객체 배열

예제코드로 살펴보자. 먼저 배열로 만들 객체를 설정해줘야한다.

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];//객체 배열 생성
		for(int i=0;i<library.length;i++) {
			System.out.println(library[i]);
			//null * 5
			//책을 가르킬 주소가 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", "조정래");
		
		for(int i = 0;i<library.length;i++) {
			System.out.println(library[i]); //주소값
		}
		
		for(int i = 0;i<library.length;i++) {
			library[i].showBookInfo(); //각 요소(메소드) 꺼내서 출력
		}
	}

}

이렇게 일일이 인덱스마다 객체를 생성해주어야 한다

배열 복사하기

  • 기존 배열과 같은거 만들거나 기존 배열이 꽉 차서 더 큰 배열로 옮길 때 사용
  • System.arraycopy(src, srcPos, dest, destPos, length)
  • 사이즈 넘어가면 오류발생...

얕은 복사(주소만 복사)

arraycopy 사용

깊은 복사(요소 값 복사)

인스턴스 다시 생성

얕은 복사, 깊은 복사 모두 한 소스코드에 담았다

package array;

public class ObjectCopy {
	public static void main(String[] args) {
		Book[] bookArr1 = new Book[3];
		Book[] bookArr2 = new Book[3];//앝은복사용
		Book[] bookArr3 = new Book[3];
		
		bookArr1[0] = new Book("태백산맥1", "조정래");
		bookArr1[1] = new Book("태백산맥2", "조정래");
		bookArr1[2] = new Book("태백산맥3", "조정래");
		
		bookArr3[0] = new Book();
		bookArr3[1] = new Book();
		bookArr3[2] = new Book();
		
		System.arraycopy(bookArr1, 0, bookArr2, 0, 3);//얕은 복사(주소복사)
		//bookArr1이 바뀌면 bookArr2도 바뀜(주소가 복사된거여서 바뀐 값을 bookArr2도 가르킨다)
		
		for(int i=0; i< bookArr2.length;i++) {//얕은복사
			//System.out.println(bookArr2[i]);
			bookArr2[i].showBookInfo();
		}
		
		//깊은복사
		for(int i=0; i<bookArr3.length;i++) {
			bookArr3[i].setAuthor(bookArr1[i].getAuthor());
			bookArr3[i].setBookName(bookArr1[i].getBookName());
		}
		
		bookArr1[0].setAuthor("나목");
		bookArr1[0].setBookName("박완서");
		
		
		
		for(int i=0; i< bookArr1.length;i++) {
			//System.out.println(bookArr2[i]);
			bookArr1[i].showBookInfo();
		}
		//얕은복사
		for(int i=0; i< bookArr2.length;i++) {
			//System.out.println(bookArr2[i]);
			bookArr2[i].showBookInfo();
		}
		
		//깊은복사 - 인스턴스 따로 잡혔기에 arr1의 변화가 arr3에 영향을 미치진 않음
		for(int i=0; i< bookArr3.length;i++) {
			//System.out.println(bookArr2[i]);
			bookArr3[i].showBookInfo();
		}
		
		
		//enhanced for loop - 전체 배열을 순회할 때 사용하면 편함
		String[] strArr = {"Java", "Android", "c"};
		for(String s:strArr) {
			System.out.println(s);
		}
		
		int[] arr = {1,2,3,4,5};
		for(int num:arr) {
			System.out.println(num);
		}
	}
}

enhanced for loop

원래는 for 문을 어떻게 썼죠?

for(int i=0;i<list.size();i++) {
			System.out.println(list.get(i));
		}

네! 이렇게 썼었죠.
불편하시죠? 불편하잖아요. 그래서 준비했습니다.

for(String s:list) {
			System.out.println(s);
		}

캬~ 빠르다 빨라
그리고 기존 for문에서 length가 아닌 size를 쓴 것은 ArrayList여서 그래요. get()을 쓴 것도 마찬가지구요.

다차원 배열

2차원 이상의 배열

  • int[][] arr = new int[2][3];
  • int[][] arr = {{1,2,3}, {4,5,6}};
package array;

public class TwoDimensionArray {
	public static void main(String[] args) {
		int[][] arr = new int[2][3];
		System.out.println(arr.length); //6이 아니라 행의 길이인 2를 출력한다
		System.out.println(arr[0].length);//행 0을 기준으로 길이가 3인 일차원 배열이기에 3을 출력
		
		int[][] arr2 = {{1,2,3}, {4,5,6}};//2중 for문으로 출력
		for(int i=0;i<arr2.length;i++) {
			for(int j=0;j<arr2[i].length;j++) {
				System.out.println(arr2[i][j]);
			}
		}
		//알파벳 13개씩 두줄 출력하려면 alphabet을 [13][2]로 만들면 좋겠죠? 해보기!!
	}
}

ArrayList 클래스

자바에서 제공되는 객체 배열이 구현된 클래스
객체 배열 편하게 관리 가능하게 메소드, 속성 등이 있음

가장 빈번한 메서드들
F1키를 누르면 help로 여러 메소드 검색 가능

package array;

import java.util.ArrayList;//import 해줘야함!!

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문과 같은 의미(출력)
		for(int i=0;i<list.size();i++) {
			System.out.println(list.get(i));
		}
	}
}

아래와 같이 사용하면 된다.
아래 코드에서 Subject라는 클래스가 쓰이는데 Subject의 코드는 생략...대충 알아먹기 가능

package array;

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+"점 입니다");
	}
}
profile
똘멩이

0개의 댓글