Java 문법 (Android)

[java] Collection - List

jasonshin 2022. 1. 20. 15:00

자바에서 제공하는 자료구조 : Collection

자료구조 : 배열과 같이 여러가지 데이터를 담아 놓고, 필요할 때마다 꺼내어 사용하기 위한 구조.

1. 순서가 있는 목록 : List형
2. 순서가 중요하지 않는 자료구조 : Set형
3. 키 - 값으로 저장되는 자료주고 : Map형

Collection (interface)
extends
List/ Set/ Map (interface)

공통 메서드
1. 데이터를 담기 위한 : add()/ addAll()
2. 데이터 확인용 : contains()/ contaninsAA()/ isEmpty()/ equals()/ size()
3. 데이터삭제 : clear()/ remove()/ removeAll()

==============================
List 인터페이스
각 데이터의 위치(순서)를 나타내는 index가 존재
index를 이용하여 원하는 위치의 데이터를 꺼내거나(get()), 삭제하거나(remove(), clear()), 변경 (set())

데이터에 대한 중복값을 허용
순서대로 데이터를 저장할 경우 주로 사용

List를 구현받은 클래스 : ArrayList

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

public static void arrayListTest() {
ArrayList<String> list = new ArrayList<String>();
list.add("grape"); //add() 맨 마지막 위치에 추가 0
list.add("orange"); // 1
list.add("Orange"); // 2 (데이터에 대한 중복 가능)
list.add("Peach"); //3

// 특정 위치에 데이터 삽입
list.add(1, "kiwi");

// 특정 위치의 데이터 변경


// 특정 위치의 데이터 제거 및 반환
String f = list.remove(0); 

// 데이터의 위치(index) 반환
int idx = list.indexOf("kiwi");

int idx2 = list.lastIndexOf("apple");


// 전체 데이터 추출
for(String s : list) {
System.out.println(s);
}
System.out.println("=============================");
for(int n=0; n<list.size(); n++) {
System.out.println(list.get(n));
}

반응형