본문 바로가기
자바(Java)/자바기초

[자바기초.011] 배열과 리스트 비교(Array vs List)

by 긱펀 2024. 3. 13.
반응형

[자바기초.011] 배열과 리스트 비교(Array vs List)

 

[1] 언제 배열 or 리스트를 사용하나? (배열과 리스트 선언하기_Declare)

  • 배열 선언(Declare Array): 저장할 데이터 타입이 같고, 개수가 정해져 있을 때
  • 리스트 선언(Declare List): 저장할 데이터 타입이 같고, 개수가 정해져 있지 않아 데이터를 삭제하거나 새롭게 추가할 때
1
2
3
4
5
6
7
8
9
 // 1.Declare an array.
    // type[] name
    int[ ] highScores = null;
    String[ ] names = null;
 
    //2.Declare an list.
    // List<Type> name. If you leave off the <Type> it will assume Object.
    List<Integer> highScoreList = null;
    List<String> nameList = null;
cs
[주의] 위 코드와 같이 배열이나 리스트를 선언(Declare)하는 것만으로는 실제로 배열과 리스트가 만들어지는 것은 아니다.배열 객체나 리스트 객체에 대한 참조(reference)만 하는 것일 뿐이다.

 

 

[2] 배열과 리스트 만들기(Creating)

  • 선언된 배열 변수를 이용해 배열을 만들기: new type[length]를 사용해 배열을 만든다.
  • 선언된 리스트 변수를 이용해 리스트 만들기: new List<Type>();을 사용해 list를 만든다.
  • 아래의 예시코드에서는 List 중에서 ArrayList를 예로 들었습니다.
1
2
3
4
5
6
7
8
9
// 1.Create an array.
    // type[] name = new type[length]
    int[ ] highScores = new int[5];
    String[ ] names = new String[5];
 
    //2.Creating an list.
    // ArrayList<Type> name = new ArrayList<Type>
    ArrayList<Integer> highScoreList = new ArrayList<Integer>();
    ArrayList<String> nameList = new ArrayList<String>();
cs
[주의] 리스트를 만들 때는 배열처럼 길이(크기)값을 넣지 않아도 된다.

 

 

[3] 배열과 리스트에 값 저장하기

  • 배열에 값(데이터)을 저장하는 방법은 name[index] = value 이다.
  • 리스트에 값(데이터)을 저장하는 방법은 name.set(index, value) 이다.
1
2
3
4
5
6
7
8
    // 1.Set the value in array
    // name[index] = value;
    highScores[0= 80;
 
 
    //2.Set the value in list
    // name.set(index,value);
    highScoreList.set(0,80);
cs

 

 

[4] 배열과 리스트의 값 가져오기

  • 배열에 저장된 값(데이터)을 가져오는 방법은 type value = name[index] 이다.
  • 리스트에 저장된 값(데이터)을 가져오는 방법은 type value = name.get(index) 이다.
1
2
3
4
5
6
7
8
     // 1.Get the value in array
    // type value = name[index];
    int score = highScores[0];
 
 
    //2.Get the value in list
    // type value = name.get(index);
    int score = highScoreList.get(0);
cs

 

 

[5] 배열과 리스트의 데이터 개수 가져오기

  • 배열의 개수 .lenth는 필드값 이므로 괄호()가 없다.
  • 리스트의 개수 .size()는 메소드 이므로 괄호()가 있다.
1
2
3
4
5
6
7
8
     // 1.Get the number of data in array
    // name.length;
    System.out.println(highScores.length);
 
 
    // 2.Get the the number of data in list
    // name.size());
    System.out.println(highScoreList.size());
cs

 

 

 


 

 

728x90
반응형

댓글