Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

[20210317] Java Arrays.asList() #70

Open
JuHyun419 opened this issue Mar 17, 2021 · 0 comments
Open

[20210317] Java Arrays.asList() #70

JuHyun419 opened this issue Mar 17, 2021 · 0 comments
Labels

Comments

@JuHyun419
Copy link
Owner

JuHyun419 commented Mar 17, 2021

Arrays.asList

  • array을 List로 변환한 후 List를 조작해야 할 때, asList를 사용하지 말자
  • Arrays에서 asList가 반환하는 ArrayList는 Arrays의 내부 클래스로, List의 구현체인 ArrayList와는 다르다.
  • Arrays 내부 ArrayList는 List를 구현하고 있지 않음.
// Arrays
public static <T> List<T> asList(T... a) {
        return new ArrayList<>(a);
    }

    /**
     * @serial include
     */
    private static class ArrayList<E> extends AbstractList<E>
        implements RandomAccess, java.io.Serializable
    { ...


// ArrayList
public class ArrayList<E> extends AbstractList<E>
        implements List<E>, RandomAccess, Cloneable, java.io.Serializable
{
    private static final long serialVersionUID = 8683452581122892189L;

  • 따라서 아래와 같이 asList로 선언하고 List를 조작할경우, 예외 발생
    public static void main(String[] args) {
        List<Integer> list = Arrays.asList(1, 2, 3, 4);
        // List<Integer> list = new ArrayList<>(Arrays.asList(1, 2, 3, 4));
        // Java 9부터는 List.of() 사용
        System.out.println(list.remove(1));
    }

Exception in thread "main" java.lang.UnsupportedOperationException
	at java.base/java.util.AbstractList.remove(AbstractList.java:167)

  • 해결책 ? new ArrayList 혹은 List.of(자바9 이상)
List<Integer> list = new ArrayList<>(Arrays.asList(1, 2, 3, 4));

List<Integer> list = List.of(1, 2, 3, 4);
@JuHyun419 JuHyun419 added the Java label Mar 17, 2021
@JuHyun419 JuHyun419 changed the title [20210317] (Java) Arrays.asList() [20210317] Java Arrays.asList() Mar 17, 2021
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
Projects
None yet
Development

No branches or pull requests

1 participant