프로그래밍/Java

Lists.newArrayList vs new ArrayList<>()

저세상 개발자 2022. 3. 25. 16:02
List<Foo<Bar, Baz>> list = Lists.newArrayList();
List<Foo<Bar, Baz>> list = new ArrayList<Foo<Bar, Baz>>();

// Java 7부터 다이아몬드 오퍼레이터를 사용하여 후자도 간단하게 표현 가능
List<Foo<Bar, Baz>> list = new ArrayList<>();

 

내부적으로도 이렇게 구현되어있어서 argument를 넘겨주지 않을 시 new ArrayList<>()와 같음

public static <T> ArrayList<T> newArrayList(Iterator<? extends T> elements) {
    if (elements == null) {
      return null;
    }
    ArrayList<T> list = newArrayList();
    while (elements.hasNext()) {
      list.add(elements.next());
    }
    return list;
  }
  
public static <T> ArrayList<T> newArrayList() {
  return new ArrayList<>();
}

 

단, List.newArrayList를 사용하면 ArrayList를 import하지 않아도 돼서 좀 더 깔끔하다는 장점이 있다..?

 

 

참고자료 - https://stackoverflow.com/questions/9980915/lists-newarraylist-vs-new-arraylist

 

Lists.newArrayList vs new ArrayList

What is the best construction for creating a List of Strings? Is it Lists.newArrayList() (from guava) or new ArrayList()? is it just a personal preference? or is it just Type generic type inferen...

stackoverflow.com