습관제작소
23-02-07 JAVA (객체 배열, 배열 복사) 본문
객체 배열
- 참조 자료형을 선언하는 객체 배열. 기본 자료형 변수 여러 개를 배열로 사용할 수 있듯이 참조 자료형 변수도 여러 개를 배열로 사용할 수 있다.
- 책의 배열로 예를 들어
연습문제
- Student
package array;
public class Student {
private String name;
private int kor;
private int eng;
private int tot;
public String getName() {
return name;
}
public Student(String name, int kor, int eng, int tot) {
super();
this.name = name;
this.kor = kor;
this.eng = eng;
this.tot = tot;
}
public void setName(String name) {
this.name = name;
}
public int getKor() {
return kor;
}
public void setKor(int kor) {
this.kor = kor;
}
public int getTot() {
return tot;
}
public void setTot(int tot) {
this.tot = tot;
}
public int getEng() {
return eng;
}
public void setEng(int eng) {
this.eng = eng;
}
public void showInfo() {
System.out.println("이름 : "+name+" 국어 : "+kor+" 영어 : "+eng+" 총점은 : "+tot);
}
}
- StudentArray
package array;
import java.util.Scanner;
public class StudentArray {
public static void main(String[] args) {
String name;
int kor;
int eng;
int tot;
Scanner sc = new Scanner(System.in);
Student[] str1 = new Student[5];
for(int i=0; i<str1.length;i++) {
System.out.println((i+1)+"번 째 학생의 이름은");
name=sc.next();
System.out.println((i+1)+"번 째 학생의 국어점수는");
kor =sc.nextInt();
System.out.println((i+1)+"번 째 학생의 영어점수는");
eng=sc.nextInt();
tot=kor+eng;
str1[i]=new Student(name,kor,eng,tot);
}
for(int i=0; i<str1.length;i++) {
str1[i].showInfo();
}
}
}
배열 복사
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("어떻게","유시민");
System.arraycopy(bookArray1,0,bookArray2,0,3);
for(int i=0; i<bookArray2.length; i++) {
bookArray2[i].showBookInfo();
bookArray1[i].showBookInfo();
System.out.println("===========");
}
}
}
'Programing Language > JAVA STUDY' 카테고리의 다른 글
23-02-06 JAVA (클래스와 객체 - static의 응용 싱글톤 패턴) (0) | 2023.02.06 |
---|---|
22-05-26 JAVA (JDBC - 회원 가입) (0) | 2022.05.29 |
22-05-23 JAVA Sort_Binery (0) | 2022.05.23 |
22-05-23 JAVA Sort_Selection (0) | 2022.05.23 |
22-05-20 JAVA 객체 (MP3) (0) | 2022.05.20 |
Comments