Web/MSA Full-Stack 과정

Kosta Day8 : this./ 배열 Array

ERE 2022. 1. 25. 18:19

- Array 배열

특징 

1. 배열은 하나의 이름으로 공간을 나누어서 여러개의 값을 저장 할 수 있다. (공간을 나누어서 번지수로 구분)

2. 단, 한가지 Type만 저장가능. 

3. 배열은 객체이다. ==> 생성해서 사용한다 (new)

4. 크기변경 안됨

5. 배열이름.length => 배열의 길이(크기)

6. 배열의 번지수는 0부터 시작 

 

*배열 생성방법

  데이터타입 [ ] 배열이름 =  new 데이터타입 [개수];

  데이터타입 배열이름 [ ] =  new 데이터타입 [개수];

  데이터타입 배열이름 [ ] =  new 데이터타입 []{값,값,값,....};

  데이터타입 배열이름 [ ] =  {값, 값, 값, ....};

 

ex ) 정수형 5개 저장하는 배열

      int [] arr = new int [5];

 

ex) 정수형 5개 저장하는 배열을 선언과 동시에 명시적 초기화 

 

 int [] arr = new int [](2,4,6,8,10);

      

===============================================================

class Test { } 존재한다 가정하에 ....

 

 

 

int i; //변수

String s;

Test t;

int arr []; // 배열

 

System.out.println(i); //0

System.out.println(s); // null   => 객체의 초기값 

System.out.println(t); // null

System.out.println(arr); // null  => 주소의 초기값이 null

 

 

i = 10;

s = "안녕";

 

t = new Test();

arr = new int [5];

 

System.out.println(i); // 10 

System.out.println(s); // 안녕

System.out.println(t); // 주소

System.out.println(arr); // 주소

 

///////////////////////////////////////////////////////////////////////////////////////////////////

 *배열에서 자주 발생하는 Exception (예외) 

: 컴파일은 성공하는 실행도중에 발생한다. 

1) ArrayIndexOutofBoundsException

 

2)NullPointerException

----------------------------------------------------------------------------

class Test{

    int a;

    public void aa(){

     }

}

 

==========================================================

*여러개 정보를 알려다 보니, 변수가 너무나도 많이 늘어난다. 

 

ex) 

   String names []  = new String [24];

   int ages [] = new int[24];

   String addrs [] = new String [24];

   

   name[0] = "장희정";

   ages[0] = 20;

   addrs[3] = "성남";

 

//VO = Value Object, DTO = Data Tranfer Object, Domain 

class Student{

       String name; 

       int age; 

       String addr;

  } 

   Student st = new Student(); //한명의 학생

   st.name = "장희정";

   st.age = 20;

   st.addr = "서울";

 

* 24명을 저장하는 Student타입의 배열을 만든 

  Student [] stArr = new Student [24]; 

stArr[0] = new Student();

stArr[1] = new Student();

..

stArr[23] = new Student();

 

stArr[0].name = "나영";

stArr[0].age = 20;

strArr[0].addr="서울"; 

 

------------------------------------------------------------------------------

* 정보은닉