List와 ArrayList의 차이

출처: Udacity

List와 ArrayList의 근본적인 차이는 무엇일까? 간단히 말하자면 List는 인터페이스고, ArrayList는 (구체적인!)클래스라는 점이다. 인터페이스인 List는 메서드가 아직 구현이 안되어있기 때문에 인스턴스화 할 수 없다. 하지만 ArrayList는 구체적인 클래스이므로 인스턴스화 할 수 있고, 지네릭 파라미터를 쓸 수 있다.

The fundamental difference here is pretty simple: List is an interface, whereas ArrayList is a concrete class. You CANNOT create an object instance of List because it’s an interface and its methods are not implemented. However, you CAN create an object instance of ArrayList and specify a generic parameter for E, because it is a concrete class.

예를들어보자. Earthquake라는 데이터타입을 가지고 ArrayList의 인스턴스 생성했다.
For example: To define an instance of an ArrayList using the Earthquake data type, you could write:
  ArrayList<Earthquake> earthquakeList = new ArrayList<Earthquake>();
위의 코드는 문제없이 작동한다. 한편, 아래와 같이 List안에도 Earthquake와 같은 데이터 타입을 저장할 수 있는것을 볼 수 있다. 
That would work fine. However, you can also store that object in a variable of data type List:
  List<Earthquake> earthquakeList = new ArrayList<Earthquake>();
이렇게 List를 사용해 위의 코드를 아래로 바꾼 이유는 유연성 때문이다.
The reason why you'd ever want to do such a thing is for flexibility:

ArrayList와 비슷한유형의 클래스로는 LinkedList가 있다. LinkedList는 List인터페이스를 구현한 클래스이다. ArrayList와 LinkedList 둘다 비슷한 메서드와 구현 전략을 갖고있다. 하지만 내부 디테일과 메모리 implication은 다르다. 어떤 이유에서 ArrayList대신 LinkedList를 사용해야하고, LinkedList를 썼을때 구현상 이점이 있다면 인스턴스를 정의한 곳으로 가서 ArrayList를 LinkedList로 바꿔주면 된다. 이런 간단한 변화만으로 아무런 문제없이 LinkedList의 장점을 취할 수 있다. (유연성의 예)
Another similar type of class to ArrayList is LinkedList, which also implements the List interface. Both classes have similar methods and implementation strategies, but somewhat different internal details and memory implications. If for some reason your app would benefit from using LinkedList instead of ArrayList, then it would be easy to just update the instance where it is defined, and then all of your List code should still work! Here's an example:
  List<Earthquake> earthquakeList = new ArrayList<Earthquake>();
  earthquakeList.add(foo);
Becomes:
  List<Earthquake> earthquakeList = new LinkedList<Earthquake>();
  earthquakeList.add(foo);
문제없이 코드가 작동한다!
And it still works!

ArrayList나 LinkedList같은 list객체를 사용하려면 대부분의 경우에서 위와같이 List를 사용하는것이 베스트 프랙티스이다.
In all cases, the best practice is to use List whenever you need a list object (whether ArrayList or LinkedList), so you can keep your code flexible.

이에대해 더 알고싶다면 링크된 문서를 읽어보길 추천한다.

To learn more about this, please read the documentation for the List interface, and check out these great discussions on StackOverflow on when to use List and when you might use ArrayList vs. LinkedList.

댓글

이 블로그의 인기 게시물

API 요청 URL(URI) 만들기(조합하기) -Uri.Builder사용하기-

TextView에 글자를 넣어주는 방법(setText, append)

텍스트 뷰의 배경을 원형 이미지로 지정하고, 배경 색상 채우기(안드로이드)