우리가 알고 있듯 배열은 같은 자료형들끼리 모아두는 하나의 묶음이자 메모리 상의 연속적인 공간이다. 따라서 이 배열에는 같은 자료형을 갖는 '객체' 또한 저장해 통합적으로 관리할 수 있다.
참고) 배열
간단한 예시를 하나 보자.
package kr.s19.object.array;
class Car{
//멤버 변수
private String color;
private int speed;
public void setColor(String color) {
this.color = color;
}
public String getColor() {
return color;
}
public void setSpeed(int speed) {
this.speed = speed;
}
public int getSpeed() {
return speed;
}
}
public class CarMain {
public static void main(String[] args) {
//배열 선언 및 생성
Car[] carArray = new Car[3];
for(int i=0;i<carArray.length;i++) {
System.out.println(carArray[i]);
}
System.out.println("===============");
carArray[0] = new Car();//객체 주소 저장
carArray[0].setColor("검정색");
carArray[0].setSpeed(100);
carArray[1] = new Car();//객체 주소 저장
carArray[1].setColor("흰색");
carArray[1].setSpeed(200);
carArray[2] = new Car();//객체 주소 저장
carArray[2].setColor("파란색");
carArray[2].setSpeed(300);
//배열의 요소 출력
for(int i=0;i<carArray.length;i++) {
System.out.println(carArray[i]);
}
System.out.println("===================");
//Car 객체의 멤버 변수에 저장된 데이터를 출력
for(int i=0;i<carArray.length;i++) {
System.out.println("carArray[" + i + "]: 색상->" + carArray[i].getColor()
+ ", 스피드->" + carArray[i].getSpeed());
}
System.out.println("===================");
for(Car car : carArray) {
System.out.println("색상: " + car.getColor()
+ ", 스피드: " + car.getSpeed());
}
}
}
배열을 선언하고 생성할 때의 구조가 똑같다.
대괄호 안에 있는 숫자는 배열의 길이이므로 객체형 배열의 경우, 저장될 수 있는 객체의 최대 개수가 된다.
[기본 자료형]
int[] it = new int[6]
→ int형 자료가 최대 6개까지 저장될 수 있는 int형 배열 it (고정 길이)[참조 자료형] = 객체형 배열
Car[] carArray = new Car[3];
→ Car 객체형 자료가 최대 3개까지 저장될 수 있는 Car형 배열 carArray (고정 길이)
객체형 배열에는 참조 변수, 즉 객체의 주소가 각각 저장되어 있다. 따라서 객체를 생성하지 않고 배열의 값을 출력할 경우, 객체가 생성되지 않아 참조할 주소가 없어 null이 출력된다.
Car[] carArray = new Car[3];
for(int i=0;i<carArray.length;i++) {
System.out.println(carArray[i]);
}
출력)
null
null
null
carArray[0] = new Car();//객체 주소 저장
carArray[0].setColor("검정색");
carArray[0].setSpeed(100);
for(int i=0;i<carArray.length;i++) {
System.out.println(carArray[i]);
}
출력)
kr.s19.object.array.Car@2f92e0f4
kr.s19.object.array.Car@28a418fc
kr.s19.object.array.Car@5305068a
for(int i=0;i<carArray.length;i++) {
System.out.println("carArray[" + i + "]: 색상->" + carArray[i].getColor()
+ ", 스피드->" + carArray[i].getSpeed());
}
출력)
carArray[0]: 색상->검정색, 스피드->100
carArray[1]: 색상->흰색, 스피드->200
carArray[2]: 색상->파란색, 스피드->300
for(Car car : carArray) {
System.out.println("색상: " + car.getColor()
+ ", 스피드: " + car.getSpeed());
}
package kr.s19.object.array;
public class Book {
private String category;
private String name;
private int price;
private double discount;
public Book() {}
public Book(String category, String name, int price, double discount) {
this.category = category;
this.name = name;
this.price = price;
this.discount = discount;
}
public String getCategory() {
return category;
}
public void setCategory(String category) {
this.category = category;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getPrice() {
return price;
}
public void setPrice(int price) {
this.price = price;
}
public double getDiscount() {
return discount;
}
public void setDiscount(double discount) {
this.discount = discount;
}
}
package kr.s19.object.array;
public class BookMain {
public static void main(String[] args) {
Book[] bookArray = new Book[3];
int total = 0;
//Book 객체를 3개 생성해서 배열에 저장
bookArray[0] = new Book("IT", "Java", 50000, 0.05);
bookArray[1] = new Book("IT", "Oracle", 40000, 0.03);
bookArray[2] = new Book("미술", "반 고흐", 60000, 0.06);
//반복문을 이용해 객체의 멤버 변수 값 출력
for(int i=0;i<bookArray.length;i++) {
System.out.printf("%s\t", bookArray[i].getCategory());
System.out.printf("%s\t", bookArray[i].getName());
System.out.printf("%,d원\t", bookArray[i].getPrice());
System.out.printf("%.2f%n", bookArray[i].getDiscount());
//합계
total += bookArray[i].getPrice();
}
System.out.printf("책 가격의 합 : %,d원%n", total);
System.out.println("========================");
//확장 for문을 이용한 출력
for(Book book : bookArray) {
System.out.printf("%s\t", book.getCategory());
System.out.printf("%s\t", book.getName());
System.out.printf("%,d원\t", book.getPrice());
System.out.printf("%.2f%%%n", book.getDiscount());
}
}
}
public Book(String category, String name, int price, double discount) {
this.category = category;
this.name = name;
this.price = price;
this.discount = discount;
}
↓
bookArray[0] = new Book("IT", "Java", 50000, 0.05);
for(int i=0;i<bookArray.length;i++) {
System.out.printf("%s\t", bookArray[i].getCategory());
System.out.printf("%s\t", bookArray[i].getName());
System.out.printf("%,d원\t", bookArray[i].getPrice());
System.out.printf("%.2f%n", bookArray[i].getDiscount());
//합계
total += bookArray[i].getPrice();
}
지금까지 배운 내용을 바탕으로 아래와 같이 실습을 진행하였다.
> 생성자, 객체형 배열을 활용해 성적 프로그램 만들기