Collections.singletonList() vs List.of()
Collections.singletonList()
μ List.of()
λ λ λ€ Javaμμ λ¨μΌ μμλ₯Ό ν¬ν¨νλ λΆλ³(immutable) 리μ€νΈλ₯Ό μμ±νλ λ©μλμ
λλ€. νμ§λ§ λͺ κ°μ§ μ°¨μ΄μ μ΄ μμ΅λλ€.
κ°λ³μ±:
Collections.singletonList()
λ‘ μμ±λ 리μ€νΈλ λ³κ²½ν μ μμ΅λλ€. μμλ₯Ό μΆκ°, μμ λλ λ³κ²½ν μ μμ΅λλ€. λ°λ©΄μList.of()
λ‘ μμ±λ 리μ€νΈλ μμ λ³κ²½ν μ μμ§λ§, μμ± νμList
μΈν°νμ΄μ€μ λ€λ₯Έ λ©μλλ₯Ό μ¬μ©νμ¬ λ¦¬μ€νΈλ₯Ό μμ ν μ μμ΅λλ€. μλ₯Ό λ€μ΄,List.of()
λ‘ μμ±λ 리μ€νΈμ μμλ₯Όset()
λ©μλλ₯Ό μ¬μ©νμ¬ λ³κ²½ν μ μμ΅λλ€.Null μμ:
Collections.singletonList()
λ μμλ‘null
μ νμ©ν©λλ€. λ°λΌμCollections.singletonList(null)
μ κ°μ΄null
μ ν¬ν¨νλ 리μ€νΈλ₯Ό μμ±ν μ μμ΅λλ€. λ°λ©΄μList.of()
λ μμλ‘null
μ νμ©νμ§ μμ΅λλ€.null
μ μ λ¬νλ©΄NullPointerException
μ΄ λ°μν©λλ€.νμ μμ μ±:
List.of()
λ κ°λ³ μΈμ(varargs)λ₯Ό μ¬μ©νμ¬ μμλ₯Ό μ λ¬ν©λλ€. μ΄λ μ»΄νμΌλ¬κ° μμμ νμ μ 체ν¬ν μ μκ² ν΄μ€λλ€. λ°λΌμ μ»΄νμΌ μμ μμ νμ μμ μ±μ 보μ₯ν μ μμ΅λλ€.Collections.singletonList()
λ λ¨μΌ μμλ₯Ό μΈμλ‘ λ°κΈ° λλ¬Έμ μ»΄νμΌλ¬κ° νμ 체ν¬λ₯Ό μννμ§ μμ΅λλ€.ꡬν μ°¨μ΄:
Collections.singletonList()
λSingletonList
ν΄λμ€μ μΈμ€ν΄μ€λ₯Ό λ°νν©λλ€. μ΄ ν΄λμ€λList
μΈν°νμ΄μ€λ₯Ό ꡬνν ν΄λμ€μ λλ€.List.of()
λList
μΈν°νμ΄μ€μ μ μ ν©ν 리 λ©μλλ‘μ, λ΄λΆμ μΌλ‘ λ³κ²½ λΆκ°λ₯ν 리μ€νΈλ₯Ό ꡬνν ν΄λμ€μ μΈμ€ν΄μ€λ₯Ό λ°νν©λλ€.
μμ½νλ©΄, Collections.singletonList()
μ List.of()
λ λ λ€ λ¨μΌ μμλ₯Ό ν¬ν¨νλ λ³κ²½ λΆκ°λ₯ν 리μ€νΈλ₯Ό μμ±νλ λ©μλμ
λλ€. κ·Έλ¬λ List.of()
λ λ νμ
μμ νλ©° null
μ νμ©νμ§ μμ΅λλ€. λν, List.of()
λ‘ μμ±λ 리μ€νΈλ μμ± νμ μμ ν μ μμ΅λλ€.
Last updated
Was this helpful?