질문 정리

왜 List<String> list = new ArrayList<>()라고 쓸까??

five2week 2023. 2. 16. 11:09

 = 업캐스팅을 하는 이유

List<String> list = new ArrayList<>();

ArrayList<String> list = new ArrayList<>();

List와 ArrayList는 다르다.

 

<List>

public interface List<E>
extends Collection<E>

<ArrayList>

public class ArrayList<E>
extends AbstractList<E>
implements List<E>, RandomAccess, Cloneable, Serializable

List는 Collection을 상속(extends) 받은 interface이고, ArrayList는 List를 상속(implements) 받은 Class이다.

기본적으로 우리가 자바에서 할당을 하는 방법이다.

 

ArrayList<String> list = new ArrayList<>();

우리는 보통 같은 타입의 객체를 생성해서 할당한다.

List<String> list = new ArrayList<>();

위와 같이 쓰는 것은 업캐스팅(upcasting)을 하는 것이다.

업캐스팅(upcasting): 자식 클래스가 부모클래스 타입으로 캐스팅되는 것

 

업캐스팅을 한다면, 자식 클래스에서만 있는 속성과 메서드를 실행하지 못한다는 단점이 있다.

그럼에도 업캐스팅을 사용하는 이유는 자바에서 지원하는 다형성을 활용해서 코드의 의존도를 낮추고, 재사용성을 높이기 위해서이다.

 

어떠한 이유로 코드를 변경하게 되었을 때(ArrayList → LinkedList)

//List<String> list = new ArrayList<>();

List<String> list = new LinkedList<>();
public List getList();
//ArrayList<String> list = new ArrayList<>();

LinkedList<String> list = new LinkedList<>();
//public ArrayList getList();

public LinkedList getList();

업캐스팅을 해서 코드를 작성하게 된다면, 이 코드를 작성한 뒤에 ArrayList를 LinkedList로 수정하는 등의 이슈에도 코드의 의존도가 낮아서 수정해야 할 부분이 적다.

 

위와 같이 업캐스팅을 했을 때는 사용하기 전 다시 다운 캐스팅을 해줘야한다.

부모 클래스로 업캐스팅된 자식 클래스를 복구해서, 자식 클래스에서만 있는 속성과 메서드를 실행할 수 있도록 해주는 것이다.

 

하지만 다운캐스팅 시 주의해야 할 점이 있다. 다운캐스팅은 컴파일시점에서 오류가 발생하지 않아도, 런타임 오류를 발생시킬 가능성이 있다. 이를 예방하기 위해서 instanceof 연산자의 도움을 받을 수 있다.

 

결론

List<String> list = new ArrayList<>();

위와 같이 작성하는 이유는 그렇게 작성하지 않으면 오류가 난다는 등의 필수적인 부분이 아니라,

선택적인 부분으로 더 좋은 프로그램을 작성하기 위한 노력 중의 일부이다.

잘못 작성한 것이 있다면 빠르게 수정하겠습니다. 감사합니다.

 

참고링크

https://stackoverflow.com/questions/9852831/polymorphism-why-use-list-list-new-arraylist-instead-of-arraylist-list-n

 

Polymorphism: Why use "List list = new ArrayList" instead of "ArrayList list = new ArrayList"?

Possible Duplicate: Why should the interface for a Java class be prefered? When should I use List<Object> list = new ArrayList<Object>(); ArrayList inherits from List, so if some

stackoverflow.com

https://docs.oracle.com/javase/8/docs/api/java/util/List.html

 

List (Java Platform SE 8 )

An ordered collection (also known as a sequence). The user of this interface has precise control over where in the list each element is inserted. The user can access elements by their integer index (position in the list), and search for elements in the lis

docs.oracle.com

https://docs.oracle.com/javase/8/docs/api/java/util/ArrayList.html

 

ArrayList (Java Platform SE 8 )

Resizable-array implementation of the List interface. Implements all optional list operations, and permits all elements, including null. In addition to implementing the List interface, this class provides methods to manipulate the size of the array that is

docs.oracle.com