728x90
반응형
MutableList는 Kotlin에서 제공하는 변경 가능한 리스트 (mutable list) 입니다.
즉, 요소를 추가, 삭제, 수정할 수 있는 리스트 타입입니다.
1. MutableList 생성 방법
mutableListOf() 또는 ArrayList() 등을 사용하여 생성할 수 있습니다.
val numbers = mutableListOf(1, 2, 3) // 변경 가능한 리스트
val names = ArrayList<String>() // Java의 ArrayList와 동일한 동작
2. 주요 함수
(1) 요소 추가 (add)
val list = mutableListOf("Apple", "Banana")
list.add("Cherry") // ["Apple", "Banana", "Cherry"]
list.add(1, "Orange") // ["Apple", "Orange", "Banana", "Cherry"]
(2) 요소 삭제 (remove, removeAt, clear)
val list = mutableListOf("A", "B", "C")
list.remove("B") // "B"를 삭제 -> ["A", "C"]
list.removeAt(0) // 인덱스 0번 삭제 -> ["C"]
list.clear() // 모든 요소 삭제 -> []
(3) 요소 수정 (set)
val list = mutableListOf(10, 20, 30)
list[1] = 25 // 인덱스 1의 값을 25로 변경 -> [10, 25, 30]
(4) 리스트 탐색 (forEach, map, filter)
val list = mutableListOf(1, 2, 3, 4, 5)
// 모든 요소 출력
list.forEach { println(it) }
// 각 요소에 2를 곱한 새 리스트 생성
val doubled = list.map { it * 2 } // [2, 4, 6, 8, 10]
// 짝수만 필터링
val evens = list.filter { it % 2 == 0 } // [2, 4]
3. List vs MutableList 차이
구분 List(불변형) MutableList(가변형)
변경 가능 여부 | ❌ (불가능) | ✅ (가능) |
추가/삭제 | ❌ (add, remove 없음) | ✅ (add, remove 사용 가능) |
수정 | ❌ (set 없음) | ✅ (set 사용 가능) |
val immutableList: List<Int> = listOf(1, 2, 3) // 변경 불가능
// immutableList.add(4) // 컴파일 오류 발생!
val mutableList: MutableList<Int> = mutableListOf(1, 2, 3) // 변경 가능
mutableList.add(4) // [1, 2, 3, 4]
4. MutableList를 List로 변환
toList()를 사용하면 MutableList를 List(불변 리스트)로 변환할 수 있습니다.
val mutableList = mutableListOf(1, 2, 3)
val readOnlyList: List<Int> = mutableList.toList() // 읽기 전용 리스트로 변환
// readOnlyList.add(4) // 컴파일 오류 발생!
5. List를 MutableList로 변환
toMutableList()를 사용하면 불변 리스트를 변경 가능한 리스트로 변환할 수 있습니다.
val readOnlyList = listOf(1, 2, 3)
val mutableList = readOnlyList.toMutableList()
mutableList.add(4) // [1, 2, 3, 4]
6. MutableList를 활용한 예제
사용자 목록 관리
data class User(val id: Int, val name: String)
fun main() {
val users = mutableListOf(
User(1, "Alice"),
User(2, "Bob")
)
// 새로운 사용자 추가
users.add(User(3, "Charlie"))
// 특정 사용자 삭제
users.removeIf { it.id == 1 }
// 사용자 목록 출력
users.forEach { println(it) }
}
출력 결과:
User(id=2, name=Bob)
User(id=3, name=Charlie)
정리
- MutableList는 요소를 추가, 삭제, 수정할 수 있는 리스트이다.
- mutableListOf()를 사용하여 생성한다.
- 주요 함수: add(), remove(), set(), clear(), map(), filter(), forEach()
- List는 변경 불가능하지만, MutableList는 변경 가능하다.
- toList(), toMutableList()를 사용하여 변경 가능/불가능 리스트 간 변환이 가능하다.
728x90
반응형
댓글