객체 배열?

choijh·2022년 10월 27일

Java+Jsp

목록 보기
7/12

객체 배열

public static void main(String[] args) {
		Student[] student = new Student[3]; // 0~2번
		
		for(int i=0; i<student.length; i++) {
			System.out.println(i + "번 인덱스: " + student[i]); 	
		}
	}

결과:				// student --->    0번 [null]
0번 인덱스: null     //  			   1번 [null]
1번 인덱스: null     //				   2번 [null]
2번 인덱스: null
  • 다음과 같이 객체 배열을 생성하여도 위치값이 저장될 메모리만 생성된다.
    -> 따라서 각 요소 객체를 생성해주어야 한다.
public static void main(String[] args) {
		Student[] student = new Student[3];
		
		for(int i=0; i<student.length; i++) {
			student[i] = new Student();
		}
		
		for(int i=0; i<student.length; i++) {
			System.out.println(i + "번 인덱스: " + student[i]); 	
		}
	}
        					    //             				student[0]
결과:							// student ---> 0번[null] ---> ([no]  
0번 인덱스: Student@515f550a     //              1번[null]       [name]   
1번 인덱스: Student@626b2d4a     //	            2번[null]       [address])
2번 인덱스: Student@5e91993f
public class Student {
	public int no;
	public String name;
	public String address;
}

0개의 댓글