본문 바로가기
Lang/Java

[Java] 1차원 리스트 List

by 상똥 2023. 4. 6.

목차

  1. 리스트란
  2. 선언
  3. 데이터 입력
  4. 데이터 삭제
  5. 데이터 및 인덱스 조회, 크기 확인
  6. 정렬 (오름차순, 내림차순)
  7. 리스트 출력

[1. List란]

  - 리스트는 중복을 허용하면서 저장순서를 유지하는 컬렉션(Collection)을 구현하는데 사용된다.

  - ArrayList : List 인터페이스를 구현하는 컬랙션 클래스

  - 인덱스는 0부터 시작

 

[2. List의 선언]

1. 빈 리스트 선언

List<Integer> list1 = new ArrayList<>();
List<Integer> list2 = new ArrayList<Integer>();
List<Integer> list3 = Collections.EMPTY_LIST;

 

2. 물리적 크기가 정해진 빈 리스트 선언

List<Integer> list = new ArrayList<>(10);

3. 선언과 동시에 데이터 입력

List<Integer> list = new ArrayList<>(Arrays.asList(1, 2, 3));

 

[3. List 데이터 입력]

1. (기본형) 리스트의 맨 끝에 데이터 삽입 : 리스트명.add(데이터);

List<Integer> list = new ArrayList<>();

list.add(1);
list.add(2);
list.add(3);

2. 특정 인덱스에 값 삽입

  - 특정 인덱스부터 그 뒤의 데이터들은 한 칸씩 밀려남

  - 선택한 인덱스에 이미 값이 있을 경우 또는 그 이전까지 값이 있을 경우에만 사용 가능

List<Integer> list = new ArrayList<>();

list.add(1);
list.add(2);
list.add(1,3);
list.add(3,1)
//list : 1, 3, 2, 1

 

[4. List 데이터 삭제]

1. 특정 인덱스의 데이터 삭제 : 리스트명.remove(인덱스);

  - 특정 인덱스의 값이 삭제되면 그 뒤의 데이터들이 한칸씩 앞으로 옮겨진다.

  - boolean형이 아니라면 인덱스 외에 데이터값을 입력하여 삭제할 수는 없다.

List<Integer> list = new ArrayList<>(Arrays.asList(1,2,3));

list.remove(0);
//list: 2, 3

2. 리스트 전체 값 삭제 : 리스트명.clear();

List<Integer> list = new ArrayList<>(Arrays.asList(1,2,3));

list.clear();

 

[5. List의 데이터 및 인덱스 조회, 크기 확인]

1. 데이터 조회 : 리스트명.get(인덱스);

List<Integer> list = new ArrayList<>(Arrays.asList(1,2,3));

int a = list.get(0);    //a=1
int b = list.get(1);    //b=2
int c = list.get(2);    //c=3

2. 데이터 검색 : 리스트명.contains(데이터);

List<Integer> list = new ArrayList<>(Arrays.asList(1, 2, 3));

boolean a = list.contains(1);   //a=true
boolean b = list.contains(5);   //b=false

3. 인덱스 검색 : 리스트명.indexOf(데이터);

List<Integer> list = new ArrayList<>(Arrays.asList(1, 2, 3));

int a = list.indexOf(2);    //a=1

4. 크기 확인 : 리스트명.size();

  - 저장된 데이터의 수를 반환 

  - 리스트의 물리적 크기(용량)와는 다른 개념

List<Integer> list = new ArrayList<>(10);
        
list.add(1);
list.add(2);
list.add(3);

int a = list.size();	//a=3

 

[6. List의 정렬]

1. 리스트의 오름차순 정렬 : Collections.sort(리스트명);

List<Integer> list = new ArrayList<>(Arrays.asList(3,2,1));

Collections.sort(list);		
//list : 1, 2, 3

2. 리스트의 내림차순 정렬 : Collections.sort(리스트명, Collections.reverseOrder);

List<Integer> list = new ArrayList<>(Arrays.asList(1,2,3));

Collections.sort(list,Collections.reverseOrder());
//list : 3, 2, 1

 

[7. List의 출력]

1. get(인덱스)를 통한 출력

List<Integer> list = new ArrayList<>(Arrays.asList(1,2,3));

for (int i = 0; i < list.size(); i++)
    System.out.println(list.get(i));

2. List+for문

List<Integer> list = new ArrayList<>(Arrays.asList(1,2,3));

for (Integer i : list)
    System.out.println(i);

1번과 2번의 결과는 동일하다

 

 

'Lang > Java' 카테고리의 다른 글

[java] 예외처리  (0) 2023.06.04
[java] 추상화와 인터페이스  (0) 2023.06.04
[java] 객체 지향 프로그래밍  (0) 2023.06.04
[Java] 2차원 리스트 List  (0) 2023.04.06
[Java] class 클래스  (0) 2023.04.03